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

遍历对象数组调用API,如何解决Promise pending问题?

问题

我有一个对象数组mergedArray,需要遍历该数组,为每个对象调用API,并将API响应设为对象的新属性。但每次操作后,数组返回的结果中都会出现industry: Promise { <pending> }。

我的代码如下:

let responseArray = await Promise.all( mergedArray.map(i =>{
  return (
    {...i, industry: atomTest()}
  )
}))
console.log(responseArray)

用于获取数据的函数如下:

const atomTest = async () => {

  await fetch('https://*********', 
  {
    method: 'POST',
    headers: {accept: 'application/json', 'content-type': 'application/json'},
    body: JSON.stringify({
      asset: {identifier: 'ticker', value: 'NKE', assetType: 'equity', market: 'USA'}
    })
  })
  .then(response => response.json())
  .then((response )=> {
    console.log(response.lists[0].name)
    return(response.lists[0].name)
  .catch(err => console.error(err));
}

如果将atomTest()替换为仅返回字符串的函数,结果是正常的。请问如何使用异步函数实现该需求?我无法让函数等待fetch结果后再继续执行。

解决方案

问题根源

当前代码中,map回调返回的是普通对象,其中industry字段直接赋值为atomTest()的调用结果——但atomTest是异步函数,调用后会立即返回一个未决状态的Promise,所以最终数组里的industry都是pending的Promise,而非API返回的实际值。

修正步骤

  1. 将map的回调改为异步函数:这样每个回调都会返回一个Promise,Promise.all就能等待所有Promise完成后,拿到最终的对象数组。
  2. 修复atomTest的语法错误:原代码中then的闭合括号位置错误,导致catch无法正确绑定;同时统一使用async/await写法,避免混合.then/.catch增加复杂度。

修正后的代码

修复atomTest函数:

const atomTest = async () => {
  try {
    const response = await fetch('https://*********', {
      method: 'POST',
      headers: {accept: 'application/json', 'content-type': 'application/json'},
      body: JSON.stringify({
        asset: {identifier: 'ticker', value: 'NKE', assetType: 'equity', market: 'USA'}
      })
    });
    const data = await response.json();
    const industryName = data.lists[0].name;
    console.log(industryName);
    return industryName;
  } catch (err) {
    console.error(err);
    // 可返回默认值避免Promise被reject导致Promise.all整体失败
    return '未知行业';
  }
};

修改数组遍历代码:

let responseArray = await Promise.all(mergedArray.map(async (i) => {
  // 等待异步请求完成,拿到实际结果后再组装对象
  const industry = await atomTest();
  return {...i, industry};
}));
console.log(responseArray);

说明

  • mergedArray.map(async (i) => { ... })会生成一个Promise数组,每个Promise最终会resolve为包含industry实际值的对象。
  • Promise.all会等待所有Promise完成后,将结果收集为数组返回,此时responseArray里的每个对象的industry字段就是API返回的实际值,而非pending的Promise。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 18:20:48