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

妖精的绣舞 提交于 2020-07-29 12:15:06

问题


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
])

回答1:


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




回答2:


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.




回答3:


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




回答4:


From my understanding Promise has a higher priority in the call stack than setTimeout, and of course synchronous code block will be the first to be executed. In that case, yes the observed behaviour above (in the order of synchronous code block, promise.resolve, and setTimeout 0) should be consistent.



来源:https://stackoverflow.com/questions/54125436/what-happens-first-settimeout-0-or-await-promise-resolve

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!