async/await function does not wait for setTimeout to finish

梦想与她 提交于 2019-12-13 19:55:56

问题


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

My code:

async function printAll() {
  await hideMoveUI();
  await startAnim();
}
printAll();

hideMoveUI = () => {
    setTimeout(() => {
      console.log('hideMoveUI');
    }, 3000);
  }

startAnim =() => {
    setTimeout(() => {
      console.log('startAnim');
    }, 500);
  }

Is setTimeout an async function?

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:


Two issues:

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

  2. 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.

Instead, give yourself a promise-enabled setTimeout and use it.

E.g.:

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...*/ });

or of course

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...*/ });


来源:https://stackoverflow.com/questions/49813405/async-await-function-does-not-wait-for-settimeout-to-finish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!