Delays between promises in promise chain

后端 未结 7 938
旧巷少年郎
旧巷少年郎 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 20:43

    The following shows an example of how you might achieve a promise that doesn't block but waits for a designated time period:

    function timedPromise(ms, payload) {
        return new Promise(function(resolve) {
            setTimeout(function() {
                resolve(payload);
            }, ms);
        })
    }
    
    
    var time = Date.now();
    
    timedPromise(1000)
        .then(function() {
            console.log(time - Date.now());
            return timedPromise(2000);
        }).then(function() {
            console.log(time - Date.now());
            return timedPromise(3000);
        });
    

    So, depending on exactly what you want, you should be able to do something like this:

    let paramerterArr = ['a','b','c','d','e','f']
    parameterArr.reduce(function(promise, item) {
      return promise.then(function(result) {
        return mySpecialFunction(item);
      }).then(function(specialResult) {
        return timedPromise(50, specialResult);
      });
    }, Promise.resolve())
    

提交回复
热议问题