Promises and more…

Aditya Narayan Gantayat
CodeX
Published in
3 min readMay 19, 2022

People often confuse Promises to be asynchronous. But are they really asynchronous? Promises are arguably the most important concept of asynchronous programming in JavaScript, however, the execution of the callbacks passed into the Promise constructor is synchronous.

Let’s understand the same with an example:

Like you can see, when the function was invoked, the callback passed into the Promise constructor executed synchronously, since it did not wait for the promise to resolve before logging ‘But I am synchronous’ to the console.
It’s the ‘.then’ chain that is executed asynchronously.

Now that begs another question !

Since the .then() block is asynchronous, does it expect a promise in return always?

The answer is NO!

When you start the .then() chain, then initial then block expects a promise in return, but thereafter, when you chain multiple then blocks, they may or may not receive a promise in return.

Let us see the same with an example:

There we go, the second then block, doesn’t receive a promise in return and yet, works just fine!

Now, as we all know, a promise can be either resolved or rejected. That arouses the curiosity as to whether we can handle the rejection of a promise inside a try/catch block or its mandatory to have a catch block chained after the then block.

Any guesses? Let’s see!

Expected this outcome or a bit surprised?
Well, JS is just like life i.e. can surprise/shock you at any moment.

When a promise is rejected, the error is caught by the catch block of the chain where the promise was expected in return.

So, we can’t use try/catch to handle rejected promises?

We can !

Async/await to the rescue!

With the implementation of async/await, we make sure the promise is either resolved/rejected right there. Once it is rejected, the catch block of the try/catch handles it, and as it returns the message, the then block which expected a promise, gets the response from an async function implicitly wrapped in a promise and logs it to the console.

While you’re here, promise me to give a clap? I am not that good a catcher, so please do not reject! xD

Cheers!

--

--