Executing callbacks in sequential order without using Promises

前端 未结 3 1304
终归单人心
终归单人心 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:14

    fns.reduceRight((acc, f) => f(acc), cb)
    

    runs

    [first, second, third, last].reduceRight((acc, f) => f(acc), second)
    

    which turns into

    ((acc, f) => f(acc))(
        ((acc, f) => f(acc))(
            ((acc, f) => f(acc))(
                 ((acc, f) => f(acc))(
                     second,
                     last
                 ),
                 third
            ),
            second
        ),
        first
    )
    

    (because that's what reduceRight does).

    The first thing to run is the innermost call,

     ((acc, f) => f(acc))(
         second,
         last
     )
    

    This becomes

    last(second)
    

    which (by the definition of last) is equivalent to

    (function () { console.log('last()'); })(second)
    

    This expression ignores second, writes last() to the console, and returns undefined.

    This leaves our expression as

    ((acc, f) => f(acc))(
        ((acc, f) => f(acc))(
            ((acc, f) => f(acc))(
                 undefined,
                 third
            ),
            second
        ),
        first
    )
    

    The next innermost call is

    ((acc, f) => f(acc))(
         undefined,
         third
    )
    

    which turns into

    third(undefined)
    

    By the definition of third this is equivalent to

    (function (cb) {
        console.log('third()');
        cb();
    })(undefined)
    

    which in turn executes

    console.log('third()');
    undefined();
    

    This writes third() to the console, then throws an exception because undefined is not a function.

提交回复
热议问题