首先发生什么:setTimeout 0或等待Promise.resolve? [英] What happens first: setTimeout 0 or await Promise.resolve?

查看:310
本文介绍了首先发生什么:setTimeout 0或等待Promise.resolve?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Node和Chrome中看到了这种行为:

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

我的问题是,这是一致的行为吗?也就是说,根据规范,在已记忆/已解决的承诺中,thenawait是否总是在setTimeout(fn, 0)之前触发?

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

推荐答案

Promise.resolve将调度微任务,而setTimeout调度宏任务.并且微任务将在运行下一个宏任务之前运行.

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

有关事件循环的更多常规信息: https://www.youtube.com/watch ?v = 8aGhZQkoFbQ

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

有关事件循环的更多技术细节: https://www.youtube.com/watch? v = cCOL7MC4Pl0

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

这篇关于首先发生什么:setTimeout 0或等待Promise.resolve?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆