【问题标题】:async/await function does not wait for setTimeout to finishasync/await 函数不等待 setTimeout 完成
【发布时间】:2018-09-23 14:26:13
【问题描述】:

我在异步函数中使用 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 函数吗?

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

【问题讨论】:

  • printAll() .then(() => hideMoveUI()) .then(() => startAnim =())
  • @Rajesh:不,不应该。
  • 这是 ES2017,不是 ES7。

标签: javascript asynchronous async-await ecmascript-2017


【解决方案1】:

两个问题:

  1. 您的hideMoveUI/startAnim 函数没有返回值,因此调用它们会产生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...*/ });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 2016-03-08
    • 2017-09-11
    相关资源
    最近更新 更多