Tyrell
Tyrell

Reputation: 13

Rewrite promises function into async function

I'm trying to rewrite promises function into async function

While my promises work

function boxColor (time) {
return new Promise ((res, rej) => {
    setTimeout(() => {
        res(box.style.backgroundColor = randomColor())
    }, time)

})}

I can't make it work with async

async function newBoxColor(time) {
try {
    setTimeout(() =>{
        return box.style.backgroundColor = randomColor()
    }, time)
} catch (error) {
    throw error
} }

What is my mistake here?

Upvotes: 0

Views: 59

Answers (1)

Quentin
Quentin

Reputation: 943571

The async keyword has two effects:

  1. It makes the function return a promise which resolves to the value returned from the function (your function doesn't have a return statement so that is undefined; the return value of the arrow function passed to setTimeout is in a different function).
  2. It allows you to use the await keyword inside that function to make it go to sleep while waiting for another promise to resolve

It is a tool to manage existing promises. It isn't helpful in converting a function which expects a callback to one which returns a promise.

You need to continue to use new Promise to get a Promise which resolves after setTimeout is done.

Upvotes: 1

Related Questions