Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Return object from Promise.all(…)

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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,
    };
  }, {});
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading