Promise.all实现其中有一个接口失败其他结果正常返回,如何实现?

好问题 👍

Promise.all 的特性是:只要有一个 Promise reject,整个 Promise.all 就会 reject,所以你看到的情况就是一个接口失败,整体就抛错了。

如果你的需求是:即使某个接口失败了,也希望其他成功的结果正常返回,有几种常见方案:


方案一:用 Promise.allSettled

ES2020 开始提供 Promise.allSettled,它会等待所有 Promise 都完成(无论成功还是失败),返回结果数组里包含每个 Promise 的状态和值:

javascript 复制代码
const reqs = [
  fetch("/api/1"),
  fetch("/api/2"),
  fetch("/api/3"),
];

Promise.allSettled(reqs).then(results => {
  results.forEach((res, i) => {
    if (res.status === "fulfilled") {
      console.log("接口", i, "成功", res.value);
    } else {
      console.log("接口", i, "失败", res.reason);
    }
  });
});

返回结果类似:

lua 复制代码
[
  { status: "fulfilled", value: ... },
  { status: "rejected", reason: ... },
  { status: "fulfilled", value: ... }
]

方案二:自己封装"永不 reject"的 Promise

如果你想继续用 Promise.all,可以把每个请求都 catch 一下,这样它们不会 reject:

less 复制代码
function wrap(promise) {
  return promise.then(
    res => ({ status: "fulfilled", value: res }),
    err => ({ status: "rejected", reason: err })
  );
}

Promise.all([
  wrap(fetch("/api/1")),
  wrap(fetch("/api/2")),
  wrap(fetch("/api/3")),
]).then(results => {
  console.log(results);
});

效果和 allSettled 一样。


方案三:只需要成功的结果

如果你完全不关心失败的接口,只要成功的值,可以这样:

javascript 复制代码
Promise.all([
  fetch("/api/1").catch(() => null),
  fetch("/api/2").catch(() => null),
  fetch("/api/3").catch(() => null),
]).then(results => {
  const validResults = results.filter(r => r !== null);
  console.log("成功的结果:", validResults);
});

✅ 推荐:如果浏览器或 Node 环境支持,直接用 Promise.allSettled,最直观清晰。

相关推荐
web小白成长日记1 天前
企业级 Vue3 + Element Plus 主题定制架构:从“能用”到“好用”的进阶之路
前端·架构
APIshop1 天前
Python 爬虫获取 item_get_web —— 淘宝商品 SKU、详情图、券后价全流程解析
前端·爬虫·python
风送雨1 天前
FastMCP 2.0 服务端开发教学文档(下)
服务器·前端·网络·人工智能·python·ai
XTTX1101 天前
Vue3+Cesium教程(36)--动态设置降雨效果
前端·javascript·vue.js
LYFlied1 天前
WebGPU与浏览器边缘智能:开启去中心化AI新纪元
前端·人工智能·大模型·去中心化·区块链
Setsuna_F_Seiei1 天前
2025 年度总结:人生重要阶段的一年
前端·程序员·年终总结
model20051 天前
alibaba linux3 系统盘网站迁移数据盘
java·服务器·前端
han_1 天前
从一道前端面试题,谈 JS 对象存储特点和运算符执行顺序
前端·javascript·面试
aPurpleBerry1 天前
React 01 目录结构、tsx 语法
前端·react.js
jayaccc1 天前
微前端架构实战全解析
前端·架构