如何修改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
相关产品推荐
相关产品推荐

