我有几个相互异步调用的函数,并且我需要在调用最后一个函数时捕获情况。 wait 语句应该调用一个我应该等待的函数,但不能直接调用它
function First(){
console.log('First is called');
setTimeout(Second(), 1000);
return;
}
function Second(){
console.log('Second is called');
}
function Main(){
First();
console.log('I called First and I want that Second also is complete');
}
我尝试使用await,但问题是我需要调用函数First(),但应该等到调用Second。并且在每次调用中都包含await似乎太复杂了,因为链长度相当大。
解决方案可能是 Main 中的无限循环,直到 Second 启动变量,但我觉得应该有更清晰的解决方案。
你可以使用 Promise。对于您的情况,您可以修改 First 和 Second 函数以返回 Promises。这样,您就可以等待 Second 完成,而不必直接调用它。
像这样
function First() {
console.log('First is called');
return new Promise(resolve => {
setTimeout(() => {
Second();
resolve(); // Resolve the promise after Second is called
}, 1000);
});
}
function Second() {
console.log('Second is called');
}
async function Main() {
await First(); // Wait for First to complete
console.log('I called First and I want that Second also is complete');
}
Main();