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.
await
beforeprintWord
means that execution ofasync
funtionrun
is paused until Promise is resolved or rejected.Function
printWord
is an async function. I'm not returning anything from it, thereforeundefined
is returned at the end of function run. Async functions always return Promises, therefore, it automatically returns Promise which automatically resolves withundefined
value? Is this what happens?Then it jumps to second
await printWord
where the same logic applies.
Am I understanding it correctly? I appreciate your help.