Chaining Asynchronous Chores Synchronously

Anisul Islam
2 min readMay 12, 2020

Promises have always been a life saver in JavaScript to deal with asynchronous stuffs in our code. ES8 introduced async/await which can be leveraged to write-up ‘synchronous’ looking asynchronous codes.

Often we embrace such use case where we need to perform multiple asynchronous tasks synchronously. For example: we have to perform Task-A and Task-B. Both the tasks are independently asynchronous. Our goal is to perform Task-A first, then Task-B. That means synchronously. Let’s go through an example implementation of a solution to achieve it.

An instance of above mentioned HandlerChain class takes multiple handler functions (these resembles the asynchronous tasks). Then we execute all asynchronous functions one by one — synchronously.

The idea here is to return Promise from each handler function (handler1, handler2, …). The keyword async before the function means one simple thing: it always returns a promise. To extend further, anything can be done inside the callback until we invoke resolve (maybe another set of asynchronous tasks? ;)

While executing all the handlers (in loop), we await for each handler’s promise to get return. Worth to mention, we can only await inside an async function. Literally, await makes JavaScript code execution wait until the promise settles. Interim, the engine can do other tasks. Meaning that await doesn’t cost CPU resources.

While dealing with promises, it’s necessary to be careful about Error Handling. If a promise resolves normally, then await promise return the result. But in case of rejection, we have to deal with the error. Let’s cut that story on another sunny day.

Say no to callbacks! :D
P.S: it’s no indifferent!

--

--