Viper
Viper

Reputation: 1387

Returning API requests within loop nodejs

I have a loop with about 15 items and need to make two api calls each time the loop is iterated through. So I need to make the API request within the loop and then do some simple calculation before the loop moves on.

Assume I have a function called getFlightData that takes 3 parameters - a departing city, arriving city, and the date. The function needs to make an API request and then return the JSON from the API call.

See my code below.

const airportsList = [
    "SFO",
    "SEA",
    "JFK",
    "YTZ"
 ]

   for (var i = 0; i < airportsList.length; i++) {
     // loop through the airports

     var departingFlightCost, returningFlightCost;
     getFlightData("MEX", airportsList[i], date1);
     getFlightData(airportsList[i],"MEX", date2);
   }


 function getFlightData(departingCity, arrivingCity, date) {
    var options = {
      method: 'GET',
      url: 'https://apidojo-kayak-v1.p.rapidapi.com/flights/create-session',
      qs: {
        origin1: departingCity,
        destination1: arrivingCity,
        departdate1: date, //'2019-12-20',
        cabin: 'e',
        currency: 'USD',
        adults: '1',
        bags: '0'
      },
      headers: {
        'x-rapidapi-host': 'apidojo-kayak-v1.p.rapidapi.com',
        'x-rapidapi-key': API_KEY
      }
    };
    request(options, function (error, response, body) {
      const flightData = body;
    });
  }

Each time the loop iterates through a city, I need to get the contents of the two API requests and then do a simple calculation before moving on. How do I most effectively do this in node?

Upvotes: 0

Views: 73

Answers (1)

Dat Le
Dat Le

Reputation: 326

You can try this:

const getFlightData = (departingCity, arrivingCity, date) => new Promise((resolve, reject) => {
  const options = {};

  request(options, (error, res) => {
    if (error) {
      return reject(error);
    }

    return resolve(res);
  });
});

const airportsList = [
  "SFO",
  "SEA",
  "JFK",
  "YTZ"
];

// things will run in parallel
for (let i = 0; i < airportsList.length; i++) {
  const date1 = new Date();
  const date2 = new Date();

  const tasks = [
    getFlightData("MEX", airportsList[i], date1),
    getFlightData(airportsList[i], "MEX", date2)
  ];

  // wait 2 tasks completed and handle
  Promise.all(tasks)
    .then(responses => {
      const res1 = responses[0];
      const res2 = responses[1];

      // continue doing something here
    })
    .catch(error => {
      // handle error here
    })
}

Or if you want everything runs step by step, you can replace for loop with this function:

const syncLoop = i => {
  const date1 = new Date();
  const date2 = new Date();

  const tasks = [
    getFlightData("MEX", airportsList[i], date1),
    getFlightData(airportsList[i], "MEX", date2)
  ];

  // wait 2 tasks completed and handle
  Promise.all(tasks)
    .then(responses => {
      const res1 = responses[0];
      const res2 = responses[1];

      // continue doing something here

      // schedule a new function
      syncLoop(i + 1);
    })
    .catch(error => {
      // handle error here
    })
};

syncLoop(0);

If you need to do something after all of async tasks were done:

const allTasks = [];
// things will run in parallel
for (let i = 0; i < airportsList.length; i++) {
  const date1 = new Date();
  const date2 = new Date();

  const tasks = [
    getFlightData("MEX", airportsList[i], date1),
    getFlightData(airportsList[i], "MEX", date2)
  ];

  // wait 2 tasks completed and handle
  allTasks.push(Promise.all(tasks)
    .then(responses => {
      const res1 = responses[0];
      const res2 = responses[1];

      // continue doing something here

      // remember to return something here
      // things will appear in the below Promise.all
      return res1;
    })
    .catch(error => {
      // handle error here
    })
  );
}

Promise.all(allTasks)
  .then(allResponses => {
    // do something when all of async tasks above were done
  })
  .catch(error => {
    // handle error here
  });

Upvotes: 1

Related Questions