Reputation: 2807
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
before printWord
means that execution of async
funtion run
is paused until Promise is resolved or rejected.
Function printWord
is an async function. I'm not returning anything from it, therefore undefined
is returned at the end of function run. Async functions always return Promises, therefore, it automatically returns Promise which automatically resolves with undefined
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.
Upvotes: 0
Views: 67
Reputation: 844
run()
function's execution is paused whenever there is an await
for it to handle. The function will pause its execution twice before resolving itself.Upvotes: 1