Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens first: setTimeout 0 or await Promise.resolve?

I'm seeing this behavior in Node and Chrome:

setTimeout(()=>{ console.log('timeout') }, 0)
Promise.resolve().then(()=>{ console.log('promise') })
console.log('sync')

// output order:
// sync
// promise
// timeout

My question is, is this consistent behavior? I.e, according to spec, does a then or await on a memoized/already resolved promise always fire before setTimeout(fn, 0)?

I want to use this in something like the following, returning one thing if I have a memoized result in my promise and another if not:

// somewhere during object initialization
this.resultingPromise = expensiveAsyncFunction()

// in a method called frequently
Promise.race([
    new Promise(resolve => setTimeout(() => resolve('default'), 0)),
    this.resultingPromise
])
like image 738
Jonas.z Avatar asked Jan 10 '19 09:01

Jonas.z


3 Answers

Promise.resolve will schedule a microtask while setTimeout schedule a macrotask. And the microtasks will run before running the next macrotask.

More information about event loop in general: https://www.youtube.com/watch?v=8aGhZQkoFbQ

More technical details about events loop: https://www.youtube.com/watch?v=cCOL7MC4Pl0

like image 61
kirill.buga Avatar answered Sep 28 '22 09:09

kirill.buga


There's no guarantee that one will be before the other. If you want to guarantee the order of execution - use Promises.

like image 26
Bwaxxlo Avatar answered Sep 28 '22 08:09

Bwaxxlo


so you have 2 async waiting States, but notice that one of them is constant and one is changing (variable). The timeout is set in an XML variable aside while the promise could took forever. If I understood your question quite well, when you have something you rely on take too long and something too short, unless you have a constant applied on one of them like the timeout, then one might end up running shorter unexpectedly (!) Be prepared for that and instead use monolithic structure from code security reasons and not performance.

like image 41
Vitali Chaim Avatar answered Sep 28 '22 09:09

Vitali Chaim