异步/等待功能不等待setTimeout完成 [英] async/await function does not wait for setTimeout to finish

查看:115
本文介绍了异步/等待功能不等待setTimeout完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在此处看到,我正在异步函数中使用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);
  }

setTimeoutasync功能吗?

如何使第二个功能等待第一个功能完成?任何帮助或建议,不胜感激.预先谢谢你.

How can I make the second function wait for the first one to finish? any help or advice is appreciated. Thank you in advance.

推荐答案

两个问题:

  1. 您的hideMoveUI/startAnim函数没有返回值,因此调用它们会导致undefined. await undefinedundefined.

  1. Your hideMoveUI/startAnim functions have no return value, so calling them results in undefined. await undefined is undefined.

如果修复#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完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆