The Actual Problem – Lack of Cooperative Multitasking

Though we endorsed the above mentioned 3 methods to handle asynchronous code, we couldn't resolve the cooperative multitasking issue that was prevalent in our User Module. This was our initial code block:

If you see, JavaScript didn't wait for a response from FirstMethod() before moving on to execute SecondMethod().

As you can imagine, this created a definite issue as we needed the response of the first function before we moved on to the next. This represents a classic disadvantage to the cooperative multitasking approach as opposed to its counterparts, preemptive multitasking or multithreading.

How did we achieve Cooperative Multitasking in Node.js?

We were looking for possible fixes and settled on using Promises with Chaining.

Using Promises with Chaining

Since we wanted more than one asynchronous operation to execute back to back and the subsequent operation should only start when it receives a response from the previous function, we went on to use "Promises with Chaining". Each promise represents the completion of another asynchronous function in the chain. What we did was that we manipulated the code to key in the promise returned from one function to the successive asynchronous function. In fact, we achieved a promise chain in two ways and it is shown below:

1. Classic

1. Modern

"Promises with chaining" approach seemed to be the best fit for our code because of its exception handling ability that allows adding try-catch blocks in processing as well as its compositional pipeline structure to handle errors. Additionally, this didn't force us to block all the methods involved like the Async/Await method with Promises and so it was the best option for our use case.

Start 1 2 3 End

Related Blog

Contact Us

*All the fields are mandatory.

+1 732 737 9188