[英]Is this a correct understanding of 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>
I've used Promise and async/await to print Hello there!
我已经使用 Promise 和 async/await 来打印
Hello there!
letter after letter with the delay of 500ms.一封接一封的邮件,延迟为 500 毫秒。 It works as intended, however, I'm not sure if I understand what happens when function
run()
executes.它按预期工作,但是,我不确定我是否理解 function
run()
执行时会发生什么。
await
before printWord
means that execution of async
funtion run
is paused until Promise is resolved or rejected.在
await
之前printWord
意味着暂停执行async
函数run
,直到 Promise 被解决或拒绝。
Function printWord
is an async function. Function
printWord
是一个异步 function。 I'm not returning anything from it, therefore undefined
is returned at the end of function run.我没有从中返回任何内容,因此在 function 运行结束时返回
undefined
。 Async functions always return Promises, therefore, it automatically returns Promise which automatically resolves with undefined
value?异步函数总是返回 Promises,因此,它会自动返回 Promise 自动解析为
undefined
的值? Is this what happens?这是怎么回事?
Then it jumps to second await printWord
where the same logic applies.然后它跳到第二个
await printWord
应用相同的逻辑。
Am I understanding it correctly?我理解正确吗? I appreciate your help.
我感谢您的帮助。
run()
function's execution is paused whenever there is an await
for it to handle.await
处理, run()
函数的执行就会暂停。 The function will pause its execution twice before resolving itself.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.