gpt4 book ai didi

javascript - 使用 http.get node.js 的 promise

转载 作者:数据小太阳 更新时间:2023-10-29 06:05:42 26 4
gpt4 key购买 nike

我正在做 nodeschool 练习,

This problem is the same as the previous problem (HTTP COLLECT) in that you need to use http.get(). However, this time you will be provided with three URLs as the first three command-line arguments.

You must collect the complete content provided to you by each of the URLs and print it to the console (stdout). You don't need to print out the length, just the data as a String; one line per URL. The catch is that you must print them out in the same order as the URLs are provided to you as command-line arguments.

换句话说,我要注册 3 个 http.get 请求,并按顺序打印从中收到的数据。

我正在尝试使用 promises = 在第一个请求未结束之前不会调用另一个获取请求。

我的代码是这样的

var http=require("http");
var collect=[];
var dat=[];
for( var i = 2 ; i < process.argv.length;i++){
collect.push(process.argv[i]);
}

function chainIt(array,callback){
return array.reduce(function(promise,item){
return promise.then(function(){
return callback(item)
})
},Promise.resolve())
}



function getIt(item){
return http.get(item,function(response){
response.on("data",function(data){
dat.push(data);
})

})
}


chainIt(collett,function(item){
return getIt(item)
})
}).then(function(){
collect.forEach(function(x){
console.log(x);
})

})

但实际上我没有打印任何数据 = 我没有通过练习。

我在这里没有看到任何错误,但我只是从 promises 和 node.js 开始。哪里错了?

最佳答案

出于教育目的,我最近为使用原生 Promisehttphttps 模块编写了一个包装器。也就是说,我建议使用库,例如​​ request ;这使事情变得更简单,具有单元测试覆盖率,由开源社区维护。此外,我的包装器对响应 block 进行了简单的字符串连接,我不认为这是构建响应主体的最佳方式。

仅供引用:这需要 Node.js 4 或更高版本,尽管方法在 Node 0.x.x 中几乎相同。

'use strict';

const http = require('http');
const url = require('url');

module.exports = {
get(url) {
return this._makeRequest('GET', url);
},

_makeRequest(method, urlString, options) {

// create a new Promise
return new Promise((resolve, reject) => {

/* Node's URL library allows us to create a
* URL object from our request string, so we can build
* our request for http.get */
const parsedUrl = url.parse(urlString);

const requestOptions = this._createOptions(method, parsedUrl);
const request = http.get(requestOptions, res => this._onResponse(res, resolve, reject));

/* if there's an error, then reject the Promise
* (can be handled with Promise.prototype.catch) */
request.on('error', reject);

request.end();
});
},

// the options that are required by http.get
_createOptions(method, url) {
return requestOptions = {
hostname: url.hostname,
path: url.path,
port: url.port,
method
};
},

/* once http.get returns a response, build it and
* resolve or reject the Promise */
_onResponse(response, resolve, reject) {
const hasResponseFailed = response.status >= 400;
var responseBody = '';

if (hasResponseFailed) {
reject(`Request to ${response.url} failed with HTTP ${response.status}`);
}

/* the response stream's (an instance of Stream) current data. See:
* https://nodejs.org/api/stream.html#stream_event_data */
response.on('data', chunk => responseBody += chunk.toString());

// once all the data has been read, resolve the Promise
response.on('end', () => resolve(responseBody));
}
};

编辑:我才刚刚意识到您是 Promise 的新手。以下是如何使用此包装器的示例:

'use strict';

const httpService = require('./httpService'); // the above wrapper

// get one URL
httpService.get('https://ron-swanson-quotes.herokuapp.com/v2/quotes').then(function gotData(data) {
console.log(data);
});

// get multiple URLs
const urls = [
'https://ron-swanson-quotes.herokuapp.com/v2/quotes',
'http://api.icndb.com/jokes/random'
];

/* map the URLs to Promises. This will actually start the
* requests, but Promise.prototype.then is always called,
* even if the operation has resolved */
const promises = urls.map(url => httpService.get(url));

Promise.all(promises).then(function gotData(responses) {
/* responses is an array containing the result of each
* Promise. This is ordered by the order of the URLs in the
* urls array */

const swansonQuote = responses[0];
const chuckNorrisQuote = responses[1];

console.log(swansonQuote);
console.log(chuckNorrisQuote);
});

关于javascript - 使用 http.get node.js 的 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35182752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com