Common gotcha’s with promises
Understand the issue with using multiple .then
calls chained together with nested async code.
Can you predict the output of the below code?
the output comes as
first
third
second
You might have expected it to be
first
second
third
The key point to understand is that:
When you attach multiple
.then
handlers, it’s not guaranteed that each.then
handler will be called only after previous.then
handler finishes if there is additional async code inside the handler.
In the above code, the second .then
handler has a setTimeout
function call with 2000 millisecond as the timeout so it will not be executed immediately, but the third .then
will be executed first as it has a 1000 millisecond timeout.
If any .then
handler is making an API call or doing some long-running process then the next .then
handler might get executed if the promise is not handled correctly.
There is a way to fix this default behavior.
We can return a new promise from the second
.then
handler and only callresolve
orreject
once we are done with our API call or any other long running process.
This will guarantee that the next .then
will always be executed after the previous one has finished.
The following is the code that will maintain the order sequence:
So understanding this will help you to avoid the unusual behavior in your code if your next .then
call is dependent on previous .then
call result.
That’s it for today. Hope you learned something new today.
Don’t forget to subscribe to get my weekly newsletter with amazing tips, tricks, and articles directly in your inbox here.