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.
 

Share:

Share on facebook
Facebook
Share on twitter
Twitter
Share on pinterest
Pinterest
Share on linkedin
LinkedIn
On Key

Related Posts

Hello world!

Welcome to WordPress. This is your first post. Edit or delete it, then start writing!

Starting from diffing algo

Introduction Are you aware of how the diffing algorithm works for react? Do you know how does the browser get to know which part of

Monoidal behavior in JavaScript

The term monoid is a bit aggressive and intimidating. In practice, though, it’s actually a very simple concept with very powerful applications not only in