Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promise vs setTimeout

I've observed that in the following code:

setTimeout(function(){console.log('setTimeout')}); Promise.resolve(1).then(function(){console.log('promise resolve')}) 

No matter how many times I execute this, the promise callback always logs before the setTimeout.

My understanding is that both callbacks are scheduled to be executed to the next tick, and I don't really understand what is going on that makes the promise always take precendence over the timeout.

like image 545
weisk Avatar asked Aug 03 '16 20:08

weisk


People also ask

What is difference between Promise and setTimeout?

Timeouts and Promises serve different purposes. setTimeout delays the execution of the code block by a specific time duration. Promises are an interface to allow async execution of code. A promise allows code to continue executing while you wait for another action to complete.

What comes first setTimeout or Promise?

setTimeout(..., 0) is called before Promise.

Why Promise is faster than callback?

Promises are the ideal choice for handling asynchronous operations in the simplest manner. They can handle multiple asynchronous operations easily and provide better error handling than callbacks and events.

Is setTimeout guaranteed?

Yet, that does not guarantee that it's immediately forwarded to the Stack and executed. setTimeout is a guarantee to a minimum time of execution.


1 Answers

Promise.resolve schedules a microtask and the setTimeout schedules a macrotask. And the microtasks are executed before running the next macrotask.

like image 94
Mohamed Gara Avatar answered Sep 24 '22 16:09

Mohamed Gara