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

Vue+Vuex中如何为Promise.allSettled结果关联对应key?

修复并发API请求结果与对应key关联的问题

方案一:将key与请求结果绑定在Promise返回值中

这种方法让每个请求的Promise完成后,直接返回包含key和请求结果的对象,确保结果与key一一对应,无需依赖顺序:

const contents = {person: {...}, info: {...}}
const promiseArray = [];

// 使用const避免var的变量提升导致的异步变量共享问题
for (const key in contents) {
  const [method, url, hash] = getters.api_props(key);
  if (method) {
    // 包装请求Promise,返回带key的结果对象
    const wrappedPromise = api[method](url, hash)
      .then(response => ({ key, result: { status: 'fulfilled', value: response } }))
      .catch(error => ({ key, result: { status: 'rejected', reason: error } }));
    promiseArray.push(wrappedPromise);
  }
}

// 直接await获取所有结果,无需嵌套then
const results = await Promise.allSettled(promiseArray);

results.forEach(item => {
  // 从返回值中取出key和对应的请求结果
  const { key, result } = item.value;
  commit("save", [key, result]);
});

// 所有请求处理完成后执行备份,无需finally
commit("backup");

方案二:利用请求列表与结果的顺序对应

如果不想包装Promise,可以先存储包含key和对应Promise的列表,再通过索引关联结果与key:

const contents = {person: {...}, info: {...}}
const requestList = [];

for (const key in contents) {
  const [method, url, hash] = getters.api_props(key);
  if (method) {
    requestList.push({
      key,
      promise: api[method](url, hash)
    });
  }
}

// 提取Promise数组执行并发请求
const settledResults = await Promise.allSettled(requestList.map(item => item.promise));

// 通过索引匹配key和结果
settledResults.forEach((result, index) => {
  const key = requestList[index].key;
  commit("save", [key, result]);
});

commit("backup");

关键优化点说明

  • 替换var为const/let:避免循环中变量提升导致的异步变量共享问题,确保每个循环迭代的key独立。
  • 移除冗余的catch:Promise.allSettled不会触发reject,因此原代码中的catch分支永远不会执行,可以删除。
  • 简化异步流程:直接使用await获取结果,避免await与then混合嵌套,提升代码可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:16:06