【发布时间】:2018-11-28 04:55:59
【问题描述】:
所以基本上我有一个带有异步函数的 for 循环。问题是程序在循环之后继续,我希望它等到在循环中调用的所有异步函数都完成后,代码才能继续。
在我的代码中,“bar”是一个 json 数组,其中包含其他 json 数组。
function write(bla) { // gets called one after another
for(var url in bla) {
asyncFunctionCall(url); // Executed about 50 times, it has to run parallel
}
// Wait for all called functions to finish before next stuff happens and
// write gets called again.
}
for(var foo in bar) {
// Here i parse the json array "foo" which is in the json array "bar"
write(foo[bla]); // bla is an array of multiple urls.
}
异步函数调用如下所示:
var request = require('request');
request(url, function (error, response, body) {
if(typeof response !== 'undefined') {
if((response.statusCode >= 400 && response.statusCode <= 451)
|| (response.statusCode >= 500 && response.statusCode <= 511))
return true;
return false;
}
return false;
});
【问题讨论】:
-
查看 Promise。
-
在这种情况下,您不能使用同步 for 循环。请参考 npm 中的库 async。它的许多功能都可以根据您的用例使用
-
我已更新 my answer 以编辑
for(var foo in bar)循环。
标签: javascript node.js loops asynchronous npm