问题
I'm using await within an async function execute functions in a particular order, if you see here - I wanted startAnim
to wait until hideMoveUI
had finished executing to execute itself.
Though my console log returns:
startAnim
hideMoveUI
My code:
async function printAll() {
await hideMoveUI();
await startAnim();
}
printAll();
hideMoveUI = () => {
setTimeout(() => {
console.log('hideMoveUI');
}, 3000);
}
startAnim =() => {
setTimeout(() => {
console.log('startAnim');
}, 500);
}
Is setTimeout
an async
function?
How can I make the second function wait for the first one to finish? any help or advice is appreciated. Thank you in advance.
回答1:
Two issues:
Your
hideMoveUI
/startAnim
functions have no return value, so calling them results inundefined
.await undefined
isundefined
.If you fix #1,
await
would be waiting on a timer handle, which on browsers is a number. There's no way forawait
to know that number is a timer handle.
Instead, give yourself a promise-enabled setTimeout and use it.
E.g.:
const wait = (delay, ...args) => new Promise(resolve => setTimeout(resolve, delay, ...args));
const hideMoveUI = () => {
return wait(3000).then(() => console.log('hideMoveUI'));
};
const startAnim = () => {
return wait(500).then(() => console.log('startAnim'));
};
async function printAll() {
await hideMoveUI();
await startAnim();
}
printAll()
.catch(e => { /*...handle error...*/ });
or of course
const wait = (delay, ...args) => new Promise(resolve => setTimeout(resolve, delay, ...args));
const hideMoveUI = async () => {
await wait(3000);
console.log('hideMoveUI');
};
const startAnim = async () => {
await wait(500);
console.log('startAnim');
};
async function printAll() {
await hideMoveUI();
await startAnim();
}
printAll()
.catch(e => { /*...handle error...*/ });
来源:https://stackoverflow.com/questions/49813405/async-await-function-does-not-wait-for-settimeout-to-finish