In my current project, I am trying to achieve a complex cycle where an HTTP GET request is executed to fetch data, followed by the creation of multiple "subrequests" based on that data. The goal is to ensure that the next iteration of the cycle begins only after all the "subrequests" have been completed. My code snippet for this task looks like:
var end = w/e; // the amount of calls I want to make
(function recursiveCall(index) {
$http.get('blahblahblah').then(function (response) { // "big" request
var requests = [];
for(var i = 0; i < whatever; i++) {
requests[i] = (function(reqIndex) { // fill the array with a series of (different) requests
return function() {
setTimeout(function() {
// use reqIndex to create a different request
$http.get('blahblahblah' + reqIndex /* some modification based on i */).then(function (data) {
// callback
}, function (data) {
// error
});
}, 1000 * reqIndex); // need to pause between each req
}
})(i)
}
Promise.all(requests.map(function (req) { // execute the array of requests
return req();
})).then(function (data) { // I want this to happen only after *all* the requests are done
// success!
console.log('all sub-requests done!');
if(index === end) {
return 0;
} else {
recursiveCall(++index); // repeat with index + 1
}
}, function (data) {
// error :(
console.log("error");
});
}, function (response) {
// error
});
})(0);
However, I have noticed that the then()
clause of Promise.all()
is executing immediately after the "big" request returns with a 200 status, without waiting for all the other subrequests to be completed. This behavior has me puzzled, and I would appreciate any insight into why this might be happening.