同步异步问题
js
async function destroy(){
console.log('destroy:start');
await testAsync(); // 使用 await 等待 testAsync 完成
console.log('destroy:end');
}
async function testAsync() {
console.log('testAsync:start');
await new Promise((resolve) => {
setTimeout(() => {
console.log('testAsync:end');
resolve();
}, 5000);
});
}
async function main() {
console.log('main:start');
await destroy(); // 使用 await 等待 testAsync 完成
console.log('main:end');
}// 要依次输出顺序: // main:start > destroy:start > testAsync:start > testAsync:end > destroy:end > main:end // 可以用 main(); // 或者 console.log('main:start'); destroy().then(() => console.log('main:end')); // 确保 'main:end' 在 destroy 完成后打印也能实现main()的顺序
