Reputation: 13
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
Reputation: 943571
The async
keyword has two effects:
return
statement so that is undefined
; the return value of the arrow function passed to setTimeout
is in a different function).await
keyword inside that function to make it go to sleep while waiting for another promise to resolveIt 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