I want to execute an HTTP GET request that fetches some data, then create a few "subrequests" to execute based on that data, and then repeat this cycle: big request, then some small requests based on the data returned from the big one. However, I want the next iteration of the cycle to start only after all of the "subrequests" are done. My code so far 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, the then()
clause of Promise.all()
seems to execute immediately after the "big" request returns with a 200; it doesn't wait for all the others to be executed. Why is this?