I am using an API to retrieve data (of several airports), based on their airport codes...
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())
)
);
}
A call like airpt(['JFK','LAX']
yields an array with results like so:
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
That's working fine. But how would I return a (single) promise from this function with all the data packaged into an object, which uses the input codes
as keys?
I know how to transform the array into an object:
array.reduce((obj, item) => {
return {
...obj,
[item['iata']]: item,
};
}, {});
I know how to do that, using .then(...)
after Promise.all()
has been resolved. However, I would like to have the repackaging into an object as part of the async function.