我有以下循环,可以发出10个请求。 console.log
将从1到10打印。如何修改此代码以仅打印peopleProfile
(10)的最终长度?
for (var i = 0; i < 10; i++) {
request(URL, function(err, response, body) {
if (err) {
console.log(err);
}
if (!err && response.statusCode == 200) {
peopleProfile.push(body);
console.log(peopleProfile.length);
}
});
}
答案 0 :(得分:2)
您可以使用Bluebird - 这个
的承诺库var promises = [];
for (var i = 0; i < 10; ++i) {
promises.push(requestAsync(url));
}
Promise.all(promises).then(function() {
console.log("print this after finishing 10 requests");
});
答案 1 :(得分:1)
有没有理由你不能这样做?
var completedRequests = 0;
for (var i = 0; i < 10; i++) {
request(URL, function(err, response, body) {
completedRequests++;
if (err) {
console.log(err);
}
if (!err && response.statusCode == 200) {
peopleProfile.push(body);
if (completedRequests === 10) {
console.log(peopleProfile.length);
}
}
});
}