Reputation: 77
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
Upvotes: 1
Views: 249
Reputation: 36609
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);
});
}
Upvotes: 4