Is there anyway to rewrite this function with async in the first function. Instead of a "new Promise"?

This is the function that is working.

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

const rainbow = async() => {
  await delayedColorChange('red', 1000);
  await delayedColorChange('orange', 1000);
  await delayedColorChange('yellow', 1000);
  await delayedColorChange('green', 1000);
  await delayedColorChange('blue', 1000);
  await delayedColorChange('indigo', 1000);
  await delayedColorChange('violet', 1000);
  await delayedColorChange('pink', 1000);
  return 'ALL DONE';
};

rainbow().then(console.log);

Trying to make delayedColorChange into an async function.

const delayedColorChange = async (color, delay) => {
  setTimeout(() => {
    document.body.style.backgroundColor = color;
  }, delay);
};

In this code the backgrounColor on the website is going straight to pink.
why is that?

Basically, is there any way to make delayedColorChange into an async function?
To my understanding, async functions returns a promise, so, why not just use an async function, instead of having to create a "new Promise" in a regular function?.

Is this even possible?

Sorry for the loaded post.

32 thoughts on “Is there anyway to rewrite this function with async in the first function. Instead of a "new Promise"?”

Leave a Comment