Executing callbacks in sequential order without using Promises

前端 未结 3 1303
终归单人心
终归单人心 2020-12-07 05:41

I am trying to execute following array (avoid callbackHell) of functions in a sequential order implementing function runCallbacksInSequence (I need to implement

3条回答
  •  没有蜡笔的小新
    2020-12-07 06:08

    Have the .reduce callback be a higher-order function, which, when called, calls the next function in the chain with the callback. At the end, you'll have a function chain that will start by calling the first function, then the second, etc:

    function first(cb) {
      console.log('first()');
      cb();
    }
    function second(cb) {
      console.log('second()');
      cb();
    }
    function third(cb) {
      console.log('third()');
      cb();
    }
    function last() {
      console.log('last()');
    }
    
    let fns = [first, second, third, last];
    
    function runCallbacksInSequence(fns, cb) {
      const chainedFns = fns.reduceRight((acc, f) => () => f(acc), cb);
      return chainedFns();
    }
    
    runCallbacksInSequence(fns);

    If you wanted the runCallbacksInSequence to accept another callback to run at the end of all of them, then:

    function first(cb) {
      console.log('first()');
      cb();
    }
    function second(cb) {
      console.log('second()');
      cb();
    }
    function third(cb) {
      console.log('third()');
      cb();
    }
    function last(cb) {
      console.log('last()');
      cb();
    }
    
    let fns = [first, second, third, last];
    
    function runCallbacksInSequence(fns, cb) {
      const chainedFns = fns.reduceRight((acc, f) => () => f(acc), cb);
      return chainedFns();
    }
    
    runCallbacksInSequence(fns, () => console.log('outer call'));

提交回复
热议问题