我正在使用 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,
};
}, {});
我知道该怎么做,使用.then(...)
afterPromise.all()
已解决。但是,我希望将重新打包到一个对象中作为异步函数的一部分。