有多个异步操作嵌套的场景,可以使用 Promise 和 async/await 来解决:
- Promise 实现异步操作的并行或者串行执行:
Promise.all([异步操作1(), 异步操作2(), 异步操作3()]).then(res => {
console.log(res);
}).catch(err => {
console.error(err);
});
或者
异步操作1().then(res1 => {
// 异步操作1执行完成后执行异步操作2
return 异步操作2();
}).then(res2 => {
// 异步操作2执行完成后执行异步操作3
return 异步操作3();
}).then(res3 => {
console.log(res3);
}).catch(err => {
console.error(err);
});
- async/await 实现异步操作的顺序执行:
async function asyncOperation() {
try {
const res1 = await 异步操作1();
const res2 = await 异步操作2();
const res3 = await 异步操作3();
console.log(res3);
} catch (err) {
console.error(err);
}
}
以上代码示例中,异步操作1、异步操作2、异步操作3 之间没有依赖关系时,可以使用 Promise.all 实现并行执行;当异步操作之间存在依赖关系时,可以使用 Promise 或 async/await 实现顺序执行。