Promise based sequence converting into Callback based

前端 未结 1 470
余生分开走
余生分开走 2021-01-28 03:43

I am trying to convert Promise based runPromiseInSequence into callback based function. Here is what I have so far. I do not quite understand how callbacks work tha

相关标签:
1条回答
  • 2021-01-28 04:08
    [f1, f2, f3, f4].reduce((promise, f) => promise.then(f), Promise.resolve(10))
    

    in your runPromiseInSequence basically boils down to

    Promise.resolve(10).then(f1).then(f2).then(f3).then(f4);
    

    This pattern doesn't work with callbacks, as there is no value to start with that we could chain on. Instead, we need to nest:

    f1(10, r1 => f2(r1, r2 => f3(r2, r3 => f4(r3, r4 => cb(r4))));
    

    This can be achieved using reduceRight:

    [f1, f2, f3, f4].reduceRight((cb, f) => r => f(r, cb), cb)(10)
    
    0 讨论(0)
提交回复
热议问题