我在Node和Chrome中看到此行为:
setTimeout(()=>{ console.log('timeout') }, 0)
Promise.resolve().then(()=>{ console.log('promise') })
console.log('sync')
// output order:
// sync
// promise
// timeout
Run Code Online (Sandbox Code Playgroud)
我的问题是,这是一致的行为吗?即,根据规范,是否已在已记忆/已解决的承诺中then或await之前始终触发setTimeout(fn, 0)?
我想在以下内容中使用它,如果我的承诺中有记忆的结果,则返回一件事,否则返回:
// somewhere during object initialization
this.resultingPromise = expensiveAsyncFunction()
// in a method called frequently
Promise.race([
new Promise(resolve => setTimeout(() => resolve('default'), 0)),
this.resultingPromise
])
Run Code Online (Sandbox Code Playgroud)