简体   繁体   English

在循环Node.js中返回API请求

[英]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. 我有一个约有15个项目的循环,每次循环迭代时都需要进行两个api调用。 So I need to make the API request within the loop and then do some simple calculation before the loop moves on. 因此,我需要在循环内发出API请求,然后在循环进行之前进行一些简单的计算。

Assume I have a function called getFlightData that takes 3 parameters - a departing city, arriving city, and the date. 假设我有一个名为getFlightData的函数,该函数带有3个参数-出发城市,到达城市和日期。 The function needs to make an API request and then return the JSON from the API call. 该函数需要发出API请求,然后从API调用返回JSON。

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. 每次循环遍历一个城市时,我需要获取两个API请求的内容,然后在继续之前进行简单的计算。 How do I most effectively do this in node? 我如何最有效地在节点上执行此操作?

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: 或者,如果您希望一切逐步进行,则可以使用以下函数替换for loop

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
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM