【问题标题】:Does await guarantee execution order without assignment in JavaScript?在 JavaScript 中没有赋值的等待是否保证执行顺序?
【发布时间】:2018-03-24 12:53:21
【问题描述】:

主题。我能说下面两段代码是相等的吗:

await someFunc() // no assignment here
doSomethingAfterSomeFunc()

和:

someFunc().then(() => 
  doSomethingAfterSomeFunc()
)

我试过了,看起来它们是相等的,但有一个疑问(例如一些优化)

【问题讨论】:

  • 不,优化不能与语义混淆。
  • 不分配使用它安全吗?如:await somePromiseToresolve();返回一些东西;

标签: javascript node.js async-await


【解决方案1】:

为了扩展Dan D's answer(因为我花了一段时间才弄清楚自己),我将多说一些关于执行流程的事情。实际上,使用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 完成时才运行链中的下一个函数。有时你希望这发生,有时你不想,有时这并不重要。但是,如果您对此一无所知,则可能需要一些时间才能弄清楚。所以我希望这个例子能帮助你理解它。

【讨论】:

    【解决方案2】:

    是的,它们完全相同,或多或少是语法糖。 await 导致执行暂停,直到等待的 Promise 得到解决。

    有关更多信息,请参阅Javascript async 重写承诺链部分。

    【讨论】:

    • 事情:这部分漏掉了没有赋值的情况。但我相信你是对的
    猜你喜欢
    • 1970-01-01
    • 2014-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-06
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多