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.
This will print the following as expected.
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.
The output will be:
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.
The output will be:
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:
Here the flow of execution is as shown below:
NOTE: This is completely differently from defining multiple then handlers for a promise.
In the above code different handlers receive the same data from the resolve callback and execute parallelly.
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.
This Promise object is now returned instead of directly returning the value as shown below:
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:
If we pass a negative value to powPromise object, the chain will break with an error as shown below.
The above code will print the following: