Noob
Noob

Reputation: 2807

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! 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.

  1. await before printWord means that execution of async funtion run is paused until Promise is resolved or rejected.

  2. 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?

  3. 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

Answers (1)

gear4
gear4

Reputation: 844

  1. Yes, the 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.
  2. Yes, an async function does return a Promise; however, realize that promises resolve, and they don't return. At least, in javascript (since async/await is just sugar for Promises) they don't really return, but they resolve.
  3. Yes.

Upvotes: 1

Related Questions