request
模块是 Node.js 中非常流行的模块,我将它用作单个非常简单的模块:
request.get("url.com", function (error, response, body) {
console.log(body);
})
非常容易处理。
想象一下,如果我有 10 个这样的请求怎么办?
var myReq1 = request.get("url.com", function (error, response, body) {
console.log(body);
})
var myReq2 = request.get("url.com", function (error, response, body) {
console.log(body);
})
var myReq3 = request.get("url.com", function (error, response, body) {
console.log(body);
})
var myReq4 = request.get("url.com", function (error, response, body) {
console.log(body);
})
.
.
.
当他们实际上都使用自己的回调函数完成时,我希望为所有人提供一个回调。
//body printed
//body printed
//body printed
//body printed
Promise.all([myReq1, myReq2, myReq3, ....]).then((values) => {
console.log(values); //
});
这是使用 Promise.all()
实现我想要的效果的正确用法吗?另外,还有一个问题是,使用
request
npm,当该特定请求的回调函数开始或结束时,promise 是否会解析?为了更清楚地说明,
request("url", (callback) => {
//Does the promise resolve here.
console.log('promise resolved now at start!')
....
console.log('promise will be resolved now after my logging')
//which one correct
})
谢谢您的解答编辑: 这是我在另一个线程中找到的一种带有 1 个承诺的方法,如何处理多个?
function doRequest(url) {
return new Promise(function (resolve, reject) {
request(url, function (error, res, body) {
if (!error && res.statusCode === 200) {
resolve(body);
} else {
reject(error);
}
});
});
}
// Usage:
async function main() {
try {
let response = await doRequest(url);
console.log(response); // `response` will be whatever you passed to `resolve()` at the top
} catch (error) {
console.error(error); // `error` will be whatever you passed to `reject()` at the top
}
}
main();
request.get(“url.com”,函数(错误,响应,正文){ 控制台.log(正文); })
var myReq1 = request.get("url.com");
var myReq2 = request.get("url.com");
var myReq3 = request.get("url.com");
var myReq4 = request.get("url.com");
Promise.all([myReq1, myReq2, myReq3, myReq4]).then((values) => {
console.log(values); // fulfilment values
});