如何先等待setTimeout完成
function a() {
setTimeout(() => {
console.log('should wait');
}, 5000);
}
async function b(c) {
console.log('hello');
await c();
}
b(a);
console.log('out');
你好
<块引用>应该等待
<块引用>出
答案 0 :(得分:3)
setTimeout
不返回 Promise,await
仅适用于 Promise。
另外,将 console.log("out")
放在 b
函数中,让它在 a
函数之后运行。
检查下面的代码片段,它可以满足您的要求。
function a() {
return new Promise((res, rej) => {
setTimeout(() => {
console.log('should wait');
res();
}, 5000);
})
}
async function b(c) {
console.log('hello');
await c();
console.log('out');
}
b(a);
答案 1 :(得分:0)
如果您希望示例正常工作,函数必须返回一个承诺(等待关键字“等待”以解决返回的承诺):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
您的示例应如下所示:
function a() {
return new Promise(resolve => {
setTimeout(resolve, 5000);
});
}
async function b(c) {
console.log('hello');
await c();
console.log('should wait');
}
await b(a);
console.log('out');
请注意,您可以在函数上使用 await
关键字,因为将函数声明为异步会自动使其返回承诺。