【发布时间】: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() 执行时会发生什么。
-
awaitbeforeprintWord表示async函数run的执行被暂停,直到 Promise 被解决或拒绝。 -
函数
printWord是一个异步函数。我没有从中返回任何内容,因此在函数运行结束时返回undefined。异步函数总是返回 Promise,因此,它会自动返回 Promise,它会自动解析为undefined值?这是怎么回事? -
然后它跳转到第二个
await printWord,同样的逻辑也适用。
我理解正确吗?感谢您的帮助。
【问题讨论】:
-
如果它像你期望的那样运行,那么是的,你理解 async/await
-
@JaromandaX 它可以运行,但我感觉就像一只猴子按按钮。
-
@JaromandaX 谢谢,我需要确保我理解正确。
-
您可以随时
console.log(await whatever())查看解析后的值。正如你所怀疑的,它在这里是未定义的。如果您使用resolve("foo"),它将记录"foo"。不过,我会使用generic pause/sleep function,而不是injectText,这是一种特殊的抽象。 -
@ggorlen 谢谢!我什至没有想到。
标签: javascript