我想执行一个HTTP GET请求来获取一些数据,然后创建一些"子请求"基于该数据执行,然后重复此循环:大请求,然后基于从大数据返回的数据的一些小请求。但是,我希望循环的下一次迭代仅在所有的"子请求"之后开始。完成。到目前为止我的代码看起来像:
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);
然而,then()
的{{1}}条款似乎是在&#34; big&#34;之后立即执行的。请求返回200;它不会等待所有其他人被执行。这是为什么?
答案 0 :(得分:1)
这里有一个示例代码来说明我的评论:
return new Promise(function(resolve, reject) {
setTimeout(function(){
// Then, in the http callback
resolve(); // or reject depending on your stuff...
}, 1000);
});
如果您使用$ q(在AngularJS应用中),请参阅documentation