简体   繁体   中英

Looping and processing two REST API calls sequentially in Nodejs

I have a list of items called projects with two folder ids. I want to loop through the list of projects, call an endpoint to get the tasks in folder 1, then call an endpoint to get the tasks in folder 2, and then merge the result. I'm having trouble making this code run in the sequential manner I'm describing above. I've tried Promises and Aysnc/Await and I can't get anything working. Here's my current code:

function processAllTasks() {
  var emptyPromise = Promise.resolve();

  for(const Project of filteredProjects){
  emptyPromise = emptyPromise.then(function() {
    return getTasksForProjectFolderID(Project.FolderID1);
  }).then(function(result) {
    console.log(result);
    array1 = result;
    getTasksForProjectFolderID(Project.FolderID2).then(function(result2) {
      console.log(result2);
      array2 = result2;
   })
  });
}
}

Where Array1 and Array2 are the two arrays I want to later merge and process. They are defined in the global scope. My rest function getTasksForProjectFolderID looks like as follows:

function getTasksForProjectFolderID(projectFolderID) {
  return rp({
    url: url + projectFolderID + '/tasks',
    headers: headers
  }).then(function(response) {
    return response;
  });
}

Where rp is const rp = require('request-promise');

As a rule of thumb, avoid defining variables in the global scope where possible. If you need an object that has the results of both queries, then that is what your function should return.

You don't need promises in your loop to solve this. Your getTasksForProjectFolderID() is already handling the asynchronous call to fetch your data.

I would do something like this (this depends on how you want to structure your return data):

function processAllTasks(filteredProjects) {
  let results = {};

  for (const projectID of filteredProjects) {
    const taskList = getTasksForProjectFolderId(projectID)
    results['Project.FolderID'] = taskList
  }
  return results;
}

Now your results object looks like this

{
  <First folder ID> : <Results of first query>,
  <Second folder ID> : <Results of second query>,
  etc...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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