Delays between promises in promise chain

后端 未结 7 941
旧巷少年郎
旧巷少年郎 2020-12-14 20:35

Let\'s say I am using the following code to run a couple of promises in series:

let paramerterArr = [\'a\',\'b\',\'c\',\'d\',\'e\',\'f\']
parameterArr.reduce         


        
相关标签:
7条回答
  • 2020-12-14 21:05

    A really handy utility function to have around is something I call delay():

    function delay(t, val) {
        return new Promise(function(resolve) {
            if (t <= 0) {
                resolve(val);
            } else {
                setTimeout(resolve.bind(null, val), t);
            }
        });
    }
    

    Then, you can use it in a promise chain like this:

    let paramerterArr = ['a','b','c','d','e','f']
    parameterArr.reduce(function(promise, item, index) {
      return promise.then(function(result) {
        // no delay on first iteration
        var delayT = index ? 50 : 0;
        return delay(delayT, item).then(mySpecialFunction);
      })
    }, Promise.resolve());
    

    You could also make a little utility function for doing the sequential iteration with optional delay:

    // delayT is optional (defaults to 0)
    function iterateSerialAsync(array, delayT, fn) {
        if (!fn) {
            fn = delayT;
            delayT = 0;
        }
        array.reduce(function(p, item, index) {
            return p.then(function() {
                // no delay on first iteration
                if (index === 0) delayT = 0;
                return delay(delayT, item).then(fn)
            });
        }, Promise.resolve());
    }
    

    And, then you would use it like this:

    iterateSerialAsync(paramerterArr, 50, mySpecialFunction).then(function(finalVal) {
        // all done here
    });
    
    0 讨论(0)
提交回复
热议问题