nodejs async: multiple dependant HTTP API calls

空扰寡人 提交于 2019-12-06 04:32:05

Using Q for promises, you can probably do something like this:

return Q
.all(course_ids.map(function(course) {
    return HTTP.GET(course); // Assuming this returns a promise
}))
.then(function(course_data) {
    var instructors = [];

    course_data.forEach(function(course) {
        var p = Q
            .all(course.instructor.map(function(instructor) {
                return HTTP.GET(instructor.id);
            }))
            .then(function(instructors) {
                course.instructors_data = instructors;

                return course;
            });

        promises.push(p);
    });

    return Q.all(promises);
});

Will resolve with an array containing the courses, each of which contains an array of instructor data in its instructors_data value.

You could use async.each(), which would do the API requests in parallel (assuming there is no concurrent API request limits on the server side, if that is the case, use async.eachLimit() instead):

async.each(instructors, function(instructor, callback) {

  // call API here, store result on `instructor`,
  // and call `callback` when done

}, function(err){
  if (err)
    console.log('An error occurred while processing instructors');
  else
    console.log('All instructors have been processed successfully');
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!