如何使用 ES6 API 重复一系列承诺

How to repeat a sequence of promises using ES6 API

我有一系列承诺,运行一个接一个。

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() 时,它 returns 一个承诺,它将在计时器到期时实现。

我怎样才能重复那个序列才能做到

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;
}