Promises Chaining

Promises can be chained, allowing multiple asynchronous operations to run in sequence. Each .then() waits for the previous promise to resolve, and the resolved value is passed to the next step in the chain.

To understand promise chaining better let us take an example of a payment flow. A payment flow is not a single action. It is a sequence of multiple asynchronus calls that happens in a specific order

Like in the example below, watch how each .then() is triggered only after the previous promise resolves.

const processPaymentFlow = () => {    createOrder()      .then(openGateway)      .then(verifySignature)      .then(updateDatabase)      .then(sendReceipt)      .catch(handleFailure)  }

Notice how every .then() runs sequentially.

Now let’s see what happens when one of the promises in the chain gets rejected.

In a promise chain, if any .then()returns a rejected promise or throws an error, the execution immediately stops and control jumps to the .catch() block.

This means all the remaining .then()blocks after the failure are skipped. They are never executed.

Notice when Verifying Signature fails the following .then() are skipped.

This above example shows how much simplicity promises bring to the complex asynchronus operations

However, the example was just for explanation purpose only in a real world payment application using this approach would compromise atomicity and lead to inconsistencies in payment.

HOME
HOME
CRAFT
CRAFT
CONTACT
CONTACT
WORK
WORK
Parth Arora
K