【问题标题】:Is this a correct understanding of async/await?这是对 async/await 的正确理解吗?
【发布时间】:2021-07-30 20:45:00
【问题描述】:

function injectText(value, selector) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      document.querySelector(selector).innerHTML = value
      resolve()
    }, 500)
  })
}

async function printWord(word, selector) {
  for (let i = 0; i < word.length; i++) {
    await injectText(word.substring(0, i + 1), selector)
  }
}

async function run() {
  await printWord('Hello', '.hello')
  await printWord('there!', '.there')
}

run()
<div class="hello"></div>
<div class="there"></div>

我已经使用 Promise 和 async/await 以 500 毫秒的延迟打印Hello there! 一个又一个字母。它按预期工作,但是,我不确定我是否理解函数 run() 执行时会发生什么。

  1. await before printWord 表示 async 函数 run 的执行被暂停,直到 Promise 被解决或拒绝。

  2. 函数printWord 是一个异步函数。我没有从中返回任何内容,因此在函数运行结束时返回undefined。异步函数总是返回 Promise,因此,它会自动返回 Promise,它会自动解析为 undefined 值?这是怎么回事?

  3. 然后它跳转到第二个await printWord,同样的逻辑也适用。

我理解正确吗?感谢您的帮助。

【问题讨论】:

  • 如果它像你期望的那样运行,那么是的,你理解 async/await
  • @JaromandaX 它可以运行,但我感觉就像一只猴子按按钮。
  • @JaromandaX 谢谢,我需要确保我理解正确。
  • 您可以随时console.log(await whatever()) 查看解析后的值。正如你所怀疑的,它在这里是未定义的。如果您使用resolve("foo"),它将记录"foo"。不过,我会使用generic pause/sleep function,而不是injectText,这是一种特殊的抽象。
  • @ggorlen 谢谢!我什至没有想到。

标签: javascript


【解决方案1】:
  1. 是的,只要有await 需要处理,run() 函数的执行就会暂停。该函数将在自行解决之前暂停执行两次。
  2. 是的,异步函数确实返回了一个 Promise;但是,请意识到承诺 resolve,它们不会返回。至少,在 javascript 中(因为 async/await 只是 Promises 的糖)它们并没有真正返回,但它们会解析。
  3. 是的。

【讨论】:

    猜你喜欢
    • 2016-01-09
    • 2017-04-10
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 2015-11-01
    • 2021-05-16
    • 2021-04-10
    • 1970-01-01
    相关资源
    最近更新 更多