gpt4 book ai didi

javascript - Promise.all 似乎并没有等待一切完成

转载 作者:行者123 更新时间:2023-12-03 09:05:23 26 4
gpt4 key购买 nike

我想执行一个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() 子句似乎在“大”请求返回 200 之后立即执行;它不会等待所有其他的都被执行。这是为什么?

最佳答案

这里有一个示例代码来说明我的评论:

return new Promise(function(resolve, reject) { 
setTimeout(function(){

// Then, in the http callback
resolve(); // or reject depending on your stuff...

}, 1000);
});

如果您使用 $q(在 AngularJS 应用程序中),请参阅 https://docs.angularjs.org/api/ng/service/%24q

关于javascript - Promise.all 似乎并没有等待一切完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32203137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com