0

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.

Noob
  • 2,247
  • 4
  • 20
  • 31
  • 1
    If it runs like you expect, then yes, you understand async/await – Jaromanda X May 09 '21 at 01:47
  • @JaromandaX It runs but I feel like a monkey pressing buttons. – Noob May 09 '21 at 01:48
  • @JaromandaX thanks, I needed to make sure I understand It correctly. – Noob May 09 '21 at 01:52
  • 2
    You can always `console.log(await whatever())` to see the resolved value. It'll be undefined here as you suspect. If you used `resolve("foo")` it'd log `"foo"`. I'd use a [generic pause/sleep function](https://stackoverflow.com/a/45628787/6243352), though, instead of `injectText` which is a sort of peculiar abstraction. – ggorlen May 09 '21 at 01:57
  • @ggorlen Thank you! I didn't even think of it. – Noob May 09 '21 at 02:05

1 Answers1

1
  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.
gear4
  • 745
  • 6
  • 13