如果您在此处看到,我正在异步函数中使用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完成
发布评论