在 javascript 中,`async` 与 `await` 无法直接对元组(tuple)类型的变量进行解构式等待,因为 `await` 操作符只能作用于单个 promise 对象。要实现类似效果,必须使用 promise.all() 将多个异步操作打包为一个 promise,该 promise 的解析结果是一个包含所有结果的数组,开发者需通过索引访问或手动解构来获取元组中的各个值。

如何并行执行多个异步函数并获取结果
要并行执行多个异步函数并获取结果,应调用 Promise.all() 并传入一个包含所有 Promise 实例的数组。该函数会并发执行这些任务,并在所有任务完成后返回一个包含对应结果的数组,其顺序与输入数组一致。

const fetchUser = async () => {
return { id: 1, name: 'Alice' };
};
const fetchPosts = async () => {
return [{ title: 'Hello' }];
};
(async () => {
const [user, posts] = await Promise.all([
fetchUser(),
fetchPosts()
]);
console.log(user.name); // Alice
console.log(posts[0].title); // Hello
})();
上述代码展示了如何将两个独立的异步调用放入 Promise.all() 中。执行后,user 变量获得第一个函数的返回值,posts 变量获得第二个函数的返回值。这种模式确保了只有在两个请求都成功时,后续逻辑才会执行。
如何处理 Promise.all() 中的错误情况
当使用 Promise.all() 时,如果其中任何一个 Promise 被拒绝(Reject),整个组合 Promise 会立即进入拒绝状态,导致后续的 catch 块捕获错误。此时,其他尚未完成的 Promise 可能仍在运行,但它们的返回值会被丢弃。

const successTask = async () => {
return 'Success';
};
const failTask = async () => {
throw new Error('Failed');
};
(async () => {
try {
const results = await Promise.all([
successTask(),
failTask()
]);
console.log(results);
} catch (error) {
console.error(error.message); // Failed
}
})();
在此示例中,尽管 successTask 能够正常完成,但由于 failTask 抛出异常,Promise.all() 整体失败。开发者可以通过检查 error 对象来处理此类情况,或者使用 Promise.allSettled() 来确保即使部分任务失败也能获取所有任务的状态。
基于 Promise.allSettled 的具体问题:如何获取混合成功与失败的结果
若需在不因单个失败而中断的情况下获取所有异步操作的结果,应使用 Promise.allSettled()。它返回一个数组,每个元素是一个描述对应 Promise 状态的对象,包含 status 属性(值为 'fulfilled' 或 'rejected')以及对应的 value 或 reason。
const task1 = async () => 'OK';
const task2 = async () => { throw new Error('Err'); };
(async () => {
const results = await Promise.allSettled([task1(), task2()]);
console.log(results[0].status); // fulfilled
console.log(results[0].value); // OK
console.log(results[1].status); // rejected
console.log(results[1].reason); // Error: Err
})();
该代码验证了 Promise.allSettled() 的行为。无论任务成功与否,都会返回结果对象。开发者可以遍历该数组,根据 status 字段分别处理成功值和错误原因,从而实现更精细的错误控制和数据聚合。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











