这是对async/await的正确理解吗



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一个接一个地打印Hello there!,延迟500ms。它按预期工作,但是,我不确定是否理解函数run()执行时会发生什么。

printWord之前的
  1. await意味着暂停执行async函数run,直到Promise被解决或拒绝。

  2. 函数printWord是一个异步函数。我没有从中返回任何内容,因此undefined在函数运行结束时返回。异步函数总是返回Promises,因此,它会自动返回Promise,而Promise是用undefined值自动解析的?这就是发生的事情吗?

  3. 然后它跳到第二个CCD_ 10,在那里应用相同的逻辑。

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

  1. 是的,只要有await需要处理,run()函数的执行就会暂停。函数将在解析自身之前暂停执行两次
  2. 是的,异步函数确实返回Promise;然而,要意识到promise解析,而它们不会返回。至少,在javascript中(因为async/await只是Promises的糖(,它们不会真正返回,但会解析
  3. 是的

最新更新