Delays between promises in promise chain

后端 未结 7 963
旧巷少年郎
旧巷少年郎 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:52

    since this seems to be a requirement of mySpecialFunction I'd implement it there. So that the function delays itself if it is called less than 50ms after the last call

    const delayBetweenCalls = (delay, fn) => {
        let lastCall = NaN;
        return function(/*...arguments*/){
            //this and arguments are both forwarded to fn
    
            return new Promise(resolve => {
                let poll = () => {
                    let delta = Date.now() - lastCall;
                    if(delta < delay){
                        setTimeout(poll, delta - delay);
                    }else{
                        lastCall = Date.now();
                        resolve( fn.apply(this, arguments) );
                    }
                }
                poll();
            })
        }
    }
    

    then:

    const mySpecialFunction = delayBetweenCalls(50, function(some, ...args){
        return someValueOrPromise;
    });
    
    //and your loop stays the same:
    parameterArr.reduce(function(promise, item) {
        return promise.then(function(result) {
            return mySpecialFunction(item);
        })
    }, Promise.resolve())
    

    so it doesn't matter where/how mySpecialFunction is called, there will always be a delay of at least 50ms before it runs the code inside the passed callback.

提交回复
热议问题