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?