【发布时间】:2021-11-21 15:05:48
【问题描述】:
我正在使用 API 根据机场代码检索(几个机场的)数据...
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())
)
);
}
像airpt(['JFK','LAX'] 这样的调用会产生一个数组,其结果如下:
Array(2)
0: {id: 3406, iata: 'JFK', icao: 'KJFK', name: 'John F. Kennedy International Airport', location: 'New York City, New York, United States', …}
1: {id: 4044, iata: 'LAX', icao: 'KLAX', name: 'Los Angeles International Airport', location: 'Los Angeles, California, United States', …}
length: 2
这很好。但是我如何从这个函数返回一个(单个)承诺,并将所有数据打包到一个对象中,该对象使用输入 codes 作为键?
我知道如何将数组转换为对象:
array.reduce((obj, item) => {
return {
...obj,
[item['iata']]: item,
};
}, {});
我知道该怎么做,在解决了Promise.all() 之后使用.then(...)。但是,我希望将重新打包到一个对象中作为异步函数的一部分。
【问题讨论】:
-
airpt返回一个承诺。您要么需要在使用reduce之前等待它,要么将reduce放在下面的then中。 -
"我知道如何使用
.then(...)来做到这一点,但是我想将其作为异步函数的一部分。" - 所以只需使用await代替.then(…)? -
@evolutionxbox ...感谢您的快速反应。我相信我了解
async/await和then的基础知识......但是我没有找到从airpt返回Promise 对象的好方法。 -
你可以做
return Promise.all(...).then(array => array.reduce(...))
标签: javascript asynchronous promise.all