【问题标题】:How to repeat a sequence of promises using ES6 API如何使用 ES6 API 重复一系列承诺
【发布时间】:2015-08-26 10:07:06
【问题描述】:

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

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

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

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

有什么建议吗?谢谢。

【问题讨论】:

    标签: javascript backbone.js ecmascript-6 es6-promise


    【解决方案1】:

    只需递归调用自己:

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

    【讨论】:

      猜你喜欢
      • 2018-10-03
      • 2017-07-14
      • 2017-03-12
      • 2018-11-28
      • 1970-01-01
      • 2018-03-18
      • 1970-01-01
      • 2016-09-02
      • 2018-07-22
      相关资源
      最近更新 更多