[英]async/await function does not wait for setTimeout to finish
如果您在此處看到,我正在異步函數內使用await按特定順序執行函數-我想讓startAnim
等到hideMoveUI
完成執行以執行自身。
盡管我的控制台日志返回:
startAnim
hideMoveUI
我的代碼:
async function printAll() {
await hideMoveUI();
await startAnim();
}
printAll();
hideMoveUI = () => {
setTimeout(() => {
console.log('hideMoveUI');
}, 3000);
}
startAnim =() => {
setTimeout(() => {
console.log('startAnim');
}, 500);
}
setTimeout
是async
函數嗎?
如何使第二個功能等待第一個功能完成? 任何幫助或建議,不勝感激。 先感謝您。
兩個問題:
您的hideMoveUI
/ startAnim
函數沒有返回值,因此調用它們將導致undefined
。 await undefined
是undefined
。
如果您修復#1, await
將在計時器句柄上等待,在瀏覽器上是一個數字。 無法await
知道該數字是計時器句柄。
而是給自己一個啟用了promise的setTimeout
並使用它。
例如:
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...*/ });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.