Blog

Set timeout 0 Vs promise


My name is Abhisek. Currently, I am working as JS Team lead in Bitcanny. As part of the work, I help juniors to understand the JS standards and echo system. During the training one of my juniors came accross that which one will execute fast if we write setTimeout with 0 and a promise. I thought it will be worthy to share the details to all of you.

Here is the sample code.

Now, he is getting confuse as I was 3 years ago. The reason behind it is very simple. setTimeout is a macrotask and Promise is microtask. Now in order to complete JS Eventloop, JS process stack and then go to the next line. Here is a secret – Micro task is always has higher priority rather than macro task. That was the reason, Promise executes first and setTimeout.

As a summary, when you are writing promise, please be careful. As, any mistake in your promise code may cause break in eventloop. That was the reason node introduces unhandledRejection hook in process level. It will help to handle any unhandled promises.

What do you think? Is there any other reason exist behined the scene? Is there any other way to handle unhandled promise? Please let us know. We will keep on posting this kind of secrets.

 






FREE Consultation

for First 100 Entrepreneurs