Promise in Node.js / JavaScript–Part II

Posted: October 13, 2021 in Javascript, Node.js
Tags: , ,

In the previous post, we have discussed about the basics of Promise, here we will take a deeper look into the Promise.then function.

The code below shows the promisified version of the add function which simply adds two numbers.

image

This will print the following as expected.

image

In the previous post we have seen that the Promise.then function comes with the following signature Promise.then(onFulfilled, onRejected). But what is the return value ? It returns another Promise object.

So what does the returned Promise object do in the code snippet above?. It does nothing but simply auto resolves without any data because the then function does not return anything.

This can be verified by invoking the then function on the Promise object returned by the invocation of the then function of the addPromise.

image

The output will be:

image

The first then function does return anything so the Promise object returned auto-resolves with an undefined value.

Now what happens if the then function returns a value? We have now changed the code so that then function of addPromise return the square of the result. Note, here we are returning simply a value not another Promise object.

image

The output will be:

image

The Promise object returned by then function call on addPromise auto-resolves with the returned value.

So if a then function returns a value then the Promise object will simply auto resolve with the returned value.

The then function returning another Promise object provides with the capability to chain the Promises and execute them in sequence as shown below:

image

Here the flow of execution is as shown below:

image

NOTE: This is completely differently from defining multiple then handlers for a promise.

image

In the above code different handlers receive the same data from the resolve callback and execute parallelly.

image

Now we will explore the condition where a then function returns another Promise object.

We have created another promisified version of Math.pow as shown below.

image

This Promise object is now returned instead of directly returning the value as shown below:

image

In this case the next then function will be executed with the fulfilment value of the returned Promise object if it is resolved or, the rejection value / error will be processed in the catch.

The above code will print the following:

image

If we pass a negative value to powPromise object, the chain will break with an error as shown below.

image

The above code will print the following:

image

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.