dan*_*mcr 1 javascript asynchronous async-await ecmascript-2017
我正在异步函数中使用等待按特定顺序执行函数,如果你看到这里 - 我想startAnim等到hideMoveUI完成执行后才能执行自己.
虽然我的控制台日志返回:
startAnim
hideMoveUI
Run Code Online (Sandbox Code Playgroud)
我的代码:
async function printAll() {
await hideMoveUI();
await startAnim();
}
printAll();
hideMoveUI = () => {
setTimeout(() => {
console.log('hideMoveUI');
}, 3000);
}
startAnim =() => {
setTimeout(() => {
console.log('startAnim');
}, 500);
}
Run Code Online (Sandbox Code Playgroud)
是setTimeout一种async功能?
如何使第二个功能等待第一个功能完成?任何帮助或建议表示赞赏.先感谢您.
两个问题:
你的hideMoveUI/ startAnim函数没有返回值,因此调用它们会导致undefined.await undefined是undefined.
如果你修复#1,await将等待一个计时器句柄,在浏览器上是一个数字.没有办法await知道这个数字是一个计时器句柄.
相反,给自己一个启用承诺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...*/ });Run Code Online (Sandbox Code Playgroud)
当然
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...*/ });Run Code Online (Sandbox Code Playgroud)