You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Promise.allSettled的成功调用结果以对象形式返回

优化Promise.allSettled成功结果的对象化返回方式

你当前的实现逻辑可行,但可以从减少索引依赖、简化代码结构、提升复用性这几个角度优化,以下是几种更优雅的方案:

方案一:绑定键与Promise,避免索引错位风险

把每个属性名对应的Promise封装成键值对数组,不用单独维护两个独立列表,彻底避免索引匹配错误的隐患:

const promisePairs = [
  ['academicPrograms', this.getAcademicPrograms()],
  ['instructionalMethods', this.getInstructionalMethods()],
  ['instructionalDeliveryMethods', this.getInstructionalDeliveryMethods()],
  ['sites', this.getSites()],
  ['statusCodes', this.getStatusCodes()],
  ['studentCode', this.getStudentCode()],
  ['studentResidencyType', this.getStudentResidencyType()],
  ['studentStatus', this.getStudentStatus()]
];

const settledResults = await Promise.allSettled(promisePairs.map(([_, promise]) => promise));

return Object.fromEntries(
  settledResults.map((result, index) => {
    if (result.status === 'fulfilled') {
      return [promisePairs[index][0], result.value];
    }
  }).filter(Boolean)
);

方案二:用reduce替代forEach简化对象构建

如果仍想分开维护属性名数组和Promise数组,用reduce可以直接在遍历过程中构建结果对象,代码更紧凑:

const objectKeys = [
  'academicPrograms',
  'instructionalMethods',
  'instructionalDeliveryMethods',
  'sites',
  'statusCodes',
  'studentCode',
  'studentResidencyType',
  'studentStatus'
];

const settledResults = await Promise.allSettled([
  this.getAcademicPrograms(),
  this.getInstructionalMethods(),
  this.getInstructionalDeliveryMethods(),
  this.getSites(),
  this.getStatusCodes(),
  this.getStudentCode(),
  this.getStudentResidencyType(),
  this.getStudentStatus()
]);

return settledResults.reduce((finalResult, item, index) => {
  if (item.status === 'fulfilled') {
    finalResult[objectKeys[index]] = item.value;
  }
  return finalResult;
}, {});

方案三:封装通用工具函数,提升复用性

如果项目中多次需要类似逻辑,封装成通用函数可以大幅减少重复代码:

async function transformSettledToObject(promisePairs) {
  const results = await Promise.allSettled(promisePairs.map(([_, p]) => p));
  return Object.fromEntries(
    results
      .map((res, idx) => res.status === 'fulfilled' ? [promisePairs[idx][0], res.value] : null)
      .filter(Boolean)
  );
}

// 调用示例
return transformSettledToObject([
  ['academicPrograms', this.getAcademicPrograms()],
  ['instructionalMethods', this.getInstructionalMethods()],
  // ...其他键值对
]);

内容的提问来源于stack exchange,提问作者Petr Schukin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 22:20:33