gpt4 book ai didi

javascript - 带延迟的顺序 Promise 循环

转载 作者:行者123 更新时间:2023-11-28 18:10:05 25 4
gpt4 key购买 nike

我正在尝试按顺序加载一组“请求”,每个请求之间由延迟分隔。

我正在使用 Promise,但由于某些原因,我在并行而不是按顺序执行请求时遇到问题。

我编写了一些测试代码,如下所示。有用!它发出请求,处理请求,超时 3 秒,然后转到第二个请求。

var batches = [of_objects];
var sequence = Promise.resolve();
var self = this;

sequence
//Create request for first batch
.then( function(){
return self._createRequestPromise(batches[0]);
})
//callback so we can update, returns nothing
.then(callback)
//add 3 sec timeout before next request
.then(function(){
return new Promise(function (resolve, reject){
setTimeout(resolve, 3000);
});
})
//Create request for second batch
.then( function(){
return self._createRequestPromise(batches[1]);
})
//callback so we can update, returns nothing
.then(callback)
//add 3 sec timeout before next request
.then(function(){
return new Promise(function (resolve, reject){
setTimeout(resolve, 3000);
});
});

return sequence;

但是,一旦我尝试将其放入任何类型的循环,我的请求就会同时触发。超时调用发生在之后。

我不确定我做错了什么,或者误解了。

//object I need to use to construct requests
var batches = [of_objects];
var sequence = Promise.resolve();
var self = this;

batches.forEach(function(batch){
sequence
//Function returns promise
.then( function(){
return self._createRequestPromise(batch); //this runs first 5x
})
//callback so we can update, returns nothing
.then(callback)
//add 3 sec timeout before next request
.then(function(){
return new Promise(function (resolve, reject){
setTimeout(resolve, 3000); //this runs after 5x
});
});
});
return sequence;

最佳答案

问题是您没有更新 sequence 以包含任何后续操作,因此所有操作都与原始已解决的 promise 相关联。没有什么可以拖延他们中的任何一个,所以他们立即执行。

您应该能够通过在每个循环上更新 sequence 变量来解决此问题,这样您就可以链接到链的末尾:

//object I need to use to construct requests
var batches = [of_objects];
var sequence = Promise.resolve();
var self = this;

batches.forEach(function (batch){
sequence = sequence // <-- here
//Function returns promise
.then( function(){
return self._createRequestPromise(batch); //this runs first 5x
})
//callback so we can update, returns nothing
.then(callback)
//add 3 sec timeout before next request
.then(function(){
return new Promise(function (resolve, reject){
setTimeout(resolve, 3000); //this runs after 5x
});
});
});

return sequence;

就我个人而言,我会尽量避免覆盖变量,因此在不重新分配变量的情况下执行此操作的另一种方法是使用 .reduce():

//object I need to use to construct requests
var batches = [of_objects];
var self = this;

return batches.reduce(function (last, batch){
return last
//Function returns promise
.then( function(){
return self._createRequestPromise(batch); //this runs first 5x
})
//callback so we can update, returns nothing
.then(callback)
//add 3 sec timeout before next request
.then(function(){
return new Promise(function (resolve, reject){
setTimeout(resolve, 3000); //this runs after 5x
});
});
}, Promise.resolve());

关于javascript - 带延迟的顺序 Promise 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41820377/

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