Is there anyway to rewrite this function with async in the first function. Instead of a “new Promise”?
No, there is not. Not if you want the function to return a promise that is tied to when the timer fires.
async
functions are very useful when you are calling functions that already return promises and you want to use await
to help with the control flow on those existing promise-returning functions.
But, when you have a function like setTimeout()
that does not use a promise at all and you want to "promisify" it so you can use promise-based control flow, you will have to use some means of making a new promise and wrapping the existing callback in that new promise. For setTimeout()
, the code you show is the standard way to do that.
It is a bit more common and generically useful to promisify just the timer because then you can use this lots of places and it is generally recommended when promisifying things to promisify at the lowest level (because it's more extensible and you build all your logic on top of promise-based control flow):
// promise-based timer
function delay(t, v) {
return new Promise(resolve => {
setTimeout(resolve, t, v);
});
}
const delayedColorChange = (color, t) => {
return delay(t).then(() => {
document.body.style.backgroundColor = color;
});
};
In this code the backgroundColor on the website is going straight to pink. why is that?
Your snippet in your question does not go straight to pink (if you just hit "run code snippet" right in your question) so if your real web page is going straight to pink, then something must be different in that implementation from this one.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…