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

如何修改async函数使Promise.all返回以机场编码为键的对象结果

实现方案

你可以直接在函数内部对Promise.all返回的结果做转换,以下是两种常用实现方式:

方式1:链式调用then处理转换

async function airpt(codes){    
  const airportCredential = {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "airport-info.p.rapidapi.com",
      "x-rapidapi-key": "xxxx"
    }
  }
  return Promise.all(
    codes
    .map(code => 
      fetch("https://airport-info.p.rapidapi.com/airport?iata="+code,airportCredential)
      .then(r => r.json())
    )
  ).then(array => 
    array.reduce((obj, item) => {
      return {
        ...obj,
        [item.iata]: item,
      };
    }, {})
  );
}

方式2:用await拿到数组后转换(更符合async/await书写习惯)

async function airpt(codes){    
  const airportCredential = {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "airport-info.p.rapidapi.com",
      "x-rapidapi-key": "xxxx"
    }
  }
  // 先等待所有接口请求完成,拿到机场信息数组
  const airportList = await Promise.all(
    codes
    .map(code => 
      fetch("https://airport-info.p.rapidapi.com/airport?iata="+code,airportCredential)
      .then(r => r.json())
    )
  )
  // 转换为以IATA编码为键的对象后返回
  return airportList.reduce((obj, item) => ({
    ...obj,
    [item.iata]: item
  }), {})
}

调用airpt(['JFK','LAX'])后返回的结果格式如下:

{
  JFK: {id: 3406, iata: 'JFK', icao: 'KJFK', name: 'John F. Kennedy International Airport', location: 'New York City, New York, United States', …},
  LAX: {id: 4044, iata: 'LAX', icao: 'KLAX', name: 'Los Angeles International Airport', location: 'Los Angeles, California, United States', …}
}

可选优化(兼容无效IATA编码场景)

如果查询的IATA编码无效,接口返回的结果可能不包含iata字段,会导致键名异常。可以调整逻辑绑定输入的编码作为兜底键:

async function airpt(codes){    
  const airportCredential = {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "airport-info.p.rapidapi.com",
      "x-rapidapi-key": "xxxx"
    }
  }
  const airportList = await Promise.all(
    codes
    .map(async code => {
      const resp = await fetch(`https://airport-info.p.rapidapi.com/airport?iata=${code}`, airportCredential)
      const data = await resp.json()
      // 存储输入的编码作为兜底
      return { inputCode: code, ...data }
    })
  )
  return airportList.reduce((obj, item) => ({
    ...obj,
    [item.inputCode]: item
  }), {})
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 23:24:04