Chaining Asynchronous Chores Synchronously
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 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!