簡體   English   中英

異步/等待功能不等待setTimeout完成

[英]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);
  }

setTimeoutasync函數嗎?

如何使第二個功能等待第一個功能完成? 任何幫助或建議,不勝感激。 先感謝您。

兩個問題:

  1. 您的hideMoveUI / startAnim函數沒有返回值,因此調用它們將導致undefined await undefinedundefined

  2. 如果您修復#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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM