Node.js | Promise Chaining
Promise chaining: Promise chaining is a syntax that allows you to chain together multiple asynchronous tasks in a specific order. This is great for complex code where one asynchronous task needs to be performed after the completion of a different asynchronous task.
To demonstrate promise chaining, the following function will be used to simulate an asynchronous task. In reality, it’s just adding up a couple of numbers, waiting two seconds, and fulfilling the promise with the sum.
Step to run the program:
- Run index.js file using below command:
With the dummy asynchronous function defined, promise chaining can be used to call add twice. The code below adds up 1 and 2 for a total of 3. It then uses the sum value 3 as the input for another call to add. The second call to add adds up 3 and 4 for a total of 7.
Promise chaining occurs when the callback function returns a promise. It allows you to chain on another then call which will run when the second promise is fulfilled. Catch can still be called to handle any errors that might occur along the way.