问题描述
如果您在此处看到,我正在异步函数中使用await按特定顺序执行函数-我希望startAnim
等到hideMoveUI
执行完毕以执行自身.
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
我的代码:
async function printAll() {
await hideMoveUI();
await startAnim();
}
printAll();
hideMoveUI = () => {
setTimeout(() => {
console.log('hideMoveUI');
}, 3000);
}
startAnim =() => {
setTimeout(() => {
console.log('startAnim');
}, 500);
}
setTimeout
是async
功能吗?
如何使第二个功能等待第一个功能完成?任何帮助或建议,不胜感激.预先谢谢你.
How can I make the second function wait for the first one to finish? any help or advice is appreciated. Thank you in advance.
推荐答案
两个问题:
-
您的
hideMoveUI
/startAnim
函数没有返回值,因此调用它们会导致undefined
.await undefined
是undefined
.
Your
hideMoveUI
/startAnim
functions have no return value, so calling them results inundefined
.await undefined
isundefined
.
如果修复#1,则await
将在计时器句柄上等待,该句柄在浏览器中为数字. await
无法知道该数字是计时器句柄.
If you fix #1, await
would be waiting on a timer handle, which on browsers is a number. There's no way for await
to know that number is a timer handle.
相反,给自己一个启用承诺的setTimeout
并使用它.
Instead, give yourself a promise-enabled setTimeout
and use it.
例如:
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...*/ });
或者当然
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...*/ });
这篇关于异步/等待功能不等待setTimeout完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!