I have this function that should make 300 requests for a web page (for benchmarking), however the Promise.all is not waiting for those requests to finish before outputting an empty array, any ideas?
function requestLoop(){
var resultSet= [];
// options.requests = 300
// options.url = http://localhost/
for(var c=1;c<=options.requests; c++){
http.get(options.url, function(res){
// resultSet.push( { request: c, statusCode: res.statusCode});
resultSet.push(new Promise(function(res){ return { request: c, statusCode: res.statusCode}; }));
});
}
Promise.all(resultSet).then(function(){
console.log(resultSet);
});
return;
}
Promise is bluebird and http is the normal http package
Promise is being pushed in array in callback. Hence By the time Promise.all
invokes, array is empty( []
)
Push new Promise
in array within loop itself, not in callback
function requestLoop() {
var resultSet = [];
for (var c = 1; c <= options.requests; c++) {
(function(c) {
resultSet.push(new Promise(function(resolve) {
http.get(options.url, function(res) {
resolve({
request: c,
statusCode: res.statusCode
});
});
}));
})(c);
}
Promise.all(resultSet).then(function() {
console.log(resultSet);
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.