async/await 函数不等待 setTimeout 完成

async/await function does not wait for setTimeout to finish

我在异步函数中使用 await 以特定顺序执行函数,如果你看到这里 - 我希望 startAnim 等到 hideMoveUI 完成执行以执行自身。

虽然我的控制台日志 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 函数吗?

如何让第二个函数等待第一个函数完成?任何帮助或建议表示赞赏。提前谢谢你。

两个问题:

  1. 您的 hideMoveUI/startAnim 函数没有 return 值,因此调用它们会导致 undefinedawait undefinedundefined.

  2. 如果您修复#1,await 将等待计时器句柄,在浏览器中它是一个数字。 await 无法知道该数字是计时器句柄。

相反,give yourself a promise-enabled 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...*/ });