gpt4 book ai didi

javascript - 如何使用 ES6 API 重复一系列 Promise

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

我有一系列依次运行的 promise 。

var Sequence = Backbone.Collection.extend({
model: Timer,

_sequence() {
return this.reduce((promise,model)=>{
return promise.then(()=>{
return model.start(); // return a Promise
});
}, Promise.resolve());
},

start(count = 1) {
// this sequence must be repeated for n times, where n is at least one
return this._sequence();
}
});

该模型是一个计时器。当我调用 model.start() 时,它会返回一个 promise ,该 promise 将在计时器到期时履行。

如何重复该序列以便我可以做到

var s1 = new Sequence([timer1, timer2, timer3]);
s1.start(2).then(function(){
// the sequence was repeated 2 times
});

有什么建议吗?谢谢。

最佳答案

只需递归调用自己:

start(count = 1) {
if (count <= 0)
return Promise.resolve();
else
return this._sequence().then(() => this.start(count - 1));
}

或者,您可以使用与 sequence 方法中相同的方法并写出循环

start(count = 1) {
var promise = Promise.resolve();
for (let i=0; i<count; i++)
promise = promise.then(() => this._sequence());
return promise;
}

关于javascript - 如何使用 ES6 API 重复一系列 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32223664/

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