![](/img/trans.png)
[英]Multiple API calls with Async & Request Package (NodeJS / Express)
[英]nodejs async: multiple dependant HTTP API calls
我正在一个项目中,该项目涉及向不同的API发出多个HTTP GET请求,每个请求都需要最后一个信息。 我正在尝试避免嵌套回调和计数器地狱,并且一直在尝试使其与async
模块一起工作。
这就是我需要做的:我有一个1..n课程标识符数组( ['2014/summer/iat/100/d100', '2014/spring/bisc/372/d100']
)。 对于数组中的每个课程,我需要通过HTTP GET获取其课程大纲。
产生的轮廓看起来像这样:
{
"info": {
"nodePath": "2014/spring/bisc/372/d100",
"number": "372",
"section": "D100",
"title": "Special Topics in Biology",
"term": "Spring 2014",
"description": "Selected topics in areas not currently offered...",
"name": "BISC 372 D100",
"dept": "BISC",
},
"instructor": [
{
"lastName": "Smith",
"commonName": "Frank",
"phone": "1 555 555-1234",
"email": "franksmith@school.edu",
"name": "Frank Smith",
"roleCode": "PI"
},
{
"lastName": "Doe",
"commonName": "John",
"phone": "1 555 555-9876",
"email": "johndoe@school.edu",
"name": "John Doe",
"roleCode": "PI"
}
]
}
(省略了一堆不相关的字段)
每个大纲对象可以包含一个instructor
属性,该属性是课程的0..n个教师对象的数组。 对于instructor
数组的每个成员,我都需要调用另一个API以获取其他数据。 当该调用返回时,我需要将其插入正确的教师对象。
最后,完成所有操作后,数据将传递到模板进行快速表达,以呈现并返回给客户端。
我尝试使用async
async.waterfall
工作,并且在仅通过获取其中一个讲者配置文件进行概念验证时(例如,不遍历数组,仅获取讲师[0])在async.waterfall
取得了一些成功。 异步模块的文档很全面,但是非常密集,我很难确定我实际需要做什么。 我有各种嵌套异步调用的Frankenstein组合,但仍然无法使用。
我真的不在乎我如何完成任务-流量控制,承诺,神奇的小精灵灰尘等等。 任何提示,不胜感激。
使用Q进行承诺,您可能可以执行以下操作:
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);
});
将解决与含有课程,其中每个都包含教师数据的在其阵列的阵列instructors_data
值。
您可以使用async.each()
,它会并行执行API请求(假设服务器端没有并发API请求限制,如果是这种情况,请改用async.eachLimit()
):
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');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.