[英]Promise.all doesn't seem to wait for everything to finish
我想執行一個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);
但是, Promise.all()
的then()
子句似乎在“ big”請求返回200之后立即執行; 它不等待其他所有命令執行。 為什么是這樣?
這里有一個示例代碼來說明我的評論:
return new Promise(function(resolve, reject) {
setTimeout(function(){
// Then, in the http callback
resolve(); // or reject depending on your stuff...
}, 1000);
});
如果您在AngularJS應用中使用$ q,請參閱https://docs.angularjs.org/api/ng/service/%24q
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.