主题。我可以说下面的两段代码是相等的吗:
await someFunc() // no assignment here
doSomethingAfterSomeFunc()
and:
someFunc().then(() =>
doSomethingAfterSomeFunc()
)
我尝试过,看起来它们是相等的,但有一个疑问(例如一些优化)
扩展至丹·D的回答 https://stackoverflow.com/a/46712242/5571789(因为我花了一段时间才搞清楚自己),我再多说几句关于执行流程的事情。确实,使用await
阻塞它所调用的方法的流程,直到它解析为止。假设我们有这个异步函数:
const someFunc = (str) => {
return new Promise(resolve => {
setTimeout(() => {
console.log('resolving promise')
resolve()
}, 1500)
})
}
因此,如果我们使用await 进行调用,如下所示:
console.log('before calling')
await someFunc()
console.log('after calling')
我们得到以下结果:
before calling
resolving promise
after calling
然而,当我们使用.then()
:
console.log('before then')
someFunc().then(() => console.log('resolved'))
console.log('after then')
有时候是这样的:
before then
after then
resolving promise
resolved
这是因为.then()
仅当前一个 Promise 完成时,才停止执行流程并运行链中的下一个函数。有时你希望这种情况发生,有时你不希望发生,有时这并不重要。但如果您不知道这一点,可能需要一些时间才能弄清楚。所以我希望这个例子能帮助你理解它。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)