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! letter after letter with the delay of 500ms. It works as intended, however, I'm not sure if I understand what happens when function run() executes.
awaitbeforeprintWordmeans that execution ofasyncfuntionrunis paused until Promise is resolved or rejected.Function
printWordis an async function. I'm not returning anything from it, thereforeundefinedis returned at the end of function run. Async functions always return Promises, therefore, it automatically returns Promise which automatically resolves withundefinedvalue? Is this what happens?Then it jumps to second
await printWordwhere the same logic applies.
Am I understanding it correctly? I appreciate your help.