NodeJS – 等待callback完成
Pusedo代码:
app.get('/', (req, res) => { request(url, callback1) //callback1 alters 'index' template a bit request(url, callback2) //callback2 alters 'index' template a bit request(url, callback3) //callback3 alters 'index' template a bit res.render('index'); //Have to render after callback1,2,3 are done });
我如何确保render
只在所有callback被解决后调用?
PS。 每个呼叫的URL都不相同。
您可以维护所有asynchronous调用的计数器,并在计数器等于asynchronous调用次数时呈现res。
下面是相同的代码片段:
app.get('/', (req, res) => { var count = 0; request(url1, function(err, data) { count++; // something to be done if(count == 3) { res.render('index'); } }); request(url2, function(err, data) { count++; // something to be done if(count == 3) { res.render('index'); } }); request(url3, function(err, data) { count++; // something to be done if(count == 3) { res.render('index'); } });
如果要在每个callback中完成的任务相同,则可以在urls上使用for循环,而不是写入不同的请求块。
你可以使用request-promise :
app.get('/', (req, res) => { request(url) .then(callback1) .then(() => request(url)) .then(callback2) .then(() => request(url)) .then(callback3) .then(() => res.render('index')); });
节点承诺模块将有所帮助。 通过使用该模块,可以在执行所有回叫后发送回应。