Skip to content Skip to sidebar Skip to footer

Implementing Sequential Callback Execution

I am trying to execute following array (avoid callbackHell) of functions(sync/async), in a sequential order, implementing function runCallbacksInSequence (I need to implement my ow

Solution 1:

In your runCallbacksInSequence you first of all have to move the x to the second position, also for consistency the final callback should be called with its first argument being null:

functionrunCallbacksInSequence(fns, cb) {
   //                                    v  v                                  vvvvvvvv
   fns.reduce((r, f) =>k =>r(acc =>f((e, x) =>k([...acc, x]))), k =>k([]))(r =>cb(null, r));
 }

If you want the first callback with an error (having the first argument set) to directly terminate the chain, you can extend your chain a bit:

//                                              vvvvvv
 fns.reduce((r, f) =>k =>r(acc =>f((e, x) => e ? cb(e) : k([...acc, x]))), k =>k([]))(r =>cb(null, r));

Solution 2:

To answer I do not quite understand how callbacks work A callback is a function that is to be executed after another function has finished executing. For example.

functionrun(cb){
  console.log("run")
  cb("okay it is running");
}

A simple function that logs stuff. How do you run it?

run()

But you want to receive the callback. To know that above cb() everything was done. You do this.

run((arg) => {
  console.log(arg) //logs "okay it is running"
});

What you actually got is a "call", "back" from the function you ran, while running it.

Post a Comment for "Implementing Sequential Callback Execution"