等待所有请求结束,承诺解析Nodejs

问题描述 投票:0回答:1

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();
    
node.js promise request
1个回答
0
投票
我已经有一段时间没有使用 Node 了,但现在还是这样。 我认为你可以选择传递回调方法或返回承诺方法,但不要尝试两者都做。

    如果您想发出请求并立即通过回调处理响应,那么您可以使用此方法:
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 });
    
© www.soinside.com 2019 - 2024. All rights reserved.