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

编程入门 行业动态 更新时间:2024-10-25 00:36:39
本文介绍了异步/等待功能不等待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); }

setTimeout是async功能吗?

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

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

推荐答案

两个问题:

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

  • 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完成

    本文发布于:2023-11-10 22:45:05,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1576669.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:功能   setTimeout

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!