1

I wanted to change the body background color to red first, and then to blue. But it's skipping the red. Got it from Colt Steele's The Web Developer Bootcamp.

function changeBG(color, delay) {
  setTimeout(() => {
    document.body.style.backgroundColor = color;
  }, delay);
}

async function init() {
  await changeBG('red', 1000);
  await changeBG('blue', 1000);
}

init();
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>
  • 2
    `changeBG()` doesn't return a promise so `await` is useless – charlietfl Mar 20 '21 at 13:56
  • 2
    Your function doesn’t return a promise to await. – jonrsharpe Mar 20 '21 at 13:56
  • 4
    Please [search thoroughly](/search?q=%5Bjs%5D+await+not+waiting) before posting. More about searching [here](/help/searching). There are dozens of questions asking why `await` isn't waiting, with dozens of answers saying (roughly) "because you're using `await` on something that isn't a promise." – T.J. Crowder Mar 20 '21 at 14:02

2 Answers2

4

You're not returning Promise from changeBG. The following will work :-

function changeBG(color, delay) {
return new Promise(resolve=>{
  setTimeout(() => {
    document.body.style.backgroundColor = color;
    resolve();
  }, delay);
})

}

async function init() {
  await changeBG('red', 1000);
  await changeBG('blue', 1000);
}

init();
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
3

You need to return Promise to use async and await.

function changeBG(color, delay) {
  return new Promise((resolve) => {
    setTimeout(() => {
      document.body.style.backgroundColor = color;
      resolve();
    }, delay);
  })
}

async function init() {
  await changeBG('red', 1000);
  await changeBG('blue', 1000);
}

init();
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Title</title>
  </head>
  <body>
    <script src="script.js"></script>
  </body>
</html>
Prime
  • 2,809
  • 1
  • 7
  • 23