Home > other >  Return object from Promise.all(...)
Return object from Promise.all(...)

Time:11-22

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.

CodePudding user response:

You seem to already have the pieces you need, so hopefully you just need to see them put together. Here's what it looks like to execute some extra code after the promise.all, and return an object based on the array:

async function airpt(codes){
  const airportCredential = {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "airport-info.p.rapidapi.com",
      "x-rapidapi-key": "xxxx"
    }
  }

  const array = await Promise.all(
    codes
    .map(code =>
      fetch("https://airport-info.p.rapidapi.com/airport?iata=" code,airportCredential)
      .then(r => r.json())
    )
  );

  return array.reduce((obj, item) => {
    return {
      ...obj,
      [item['iata']]: item,
    };
  }, {});
}
  • Related