我需要同步实现 REST API,以便它返回对象列表。因此顶层方法的实现如下,其中方法listObjs()应该同步执行,并返回可用的对象,以便可以在REST响应中返回它们。
var objs= mds.listObjs();
console.log("Leaving the GET /objs API!! ["+objs+"]");
res.json({ message :'"Leaving the GET /objs API!! ['+objs+']'})
在方法 listObjs() 中,我使用 async.series 将处理分成多个阶段,一个接一个地执行。第一阶段将获取对象,第二阶段将处理它们并将子集返回给调用者。 getHttpRequest 方法在内部使用回调来捕获请求的结果。可以看出,我正在使用此回调来执行异步回调。这应该通知 async.series 进入下一阶段。
listObjs : function() {
async.series([
function (callback) {
console.log("Before getHttp");
getHttpRequest(httpQuery,
function(responseStatusCode, objectsJson) {
console.log("Now Trigger the next async step")
callback(null, objectsJson); // trigger next step
});
console.log("After getHttp");
},
function (callback) {
console.log("Next Step, process the returned Objects");
callback(null, "2");
}
],
function (err, result) {
console.log("At end of async block "+result);
});
console.log("Leaving listObjs, SHOULD BE AFTER THE NEXT STEP IS CALLED");
},
我观察到 async.series block 不会等到其回调被调用。相反,执行线程似乎跳出了异步 block ,并且顶级方法在其结果可用之前返回。:-
- 在 getHttp 之前
- getHttp 之后
- 离开 listObjs,应该在调用下一步之后
- 离开 GET/objs API! []
- 现在触发下一个异步步骤
- 下一步,处理返回的对象,result=
- 在异步 block 末尾 [{"name":"obj1"},{"name":"obj2"}],2
那么为什么 async.series block 在执行第二阶段之前就退出了? 也就是说,为什么消息 4. 不在我的跟踪消息的末尾?
提前非常感谢
最佳答案
输出正确!它们是异步的,当它们自己的任务完成时它们将被执行。这是您的完整代码
var data = {};
var getData = function (callback) {
// this is asyn task, it will take time to complete
getHttpRequest(httpQuery, function(responseStatusCode, objectsJson) {
// save your data
data = objectsJson;
callback(null, objectsJson); // trigger next step, objectsJson will be avaible at the last callback
});
// meanwhile this line will be executed
console.log("I will be executed");
}
var processData = function (callback) {
// do your job here, with data varibale
// callback(err, result)
// if you envoke callback with error then next function of the async.series will not be executed
if(someThingGoWrong)
return callback(new Error("Your error")); // TagOne
}
var anotherTask = function(callback){
if(someThingGoWrong)
return callback("You can also send error as a string"); // TagTwo
// another tasks
data = updatedValues
}
var finalHandler = function (err, result) {
// if any error happen in TagOne or TagTwo
// this final handler will be immediate executed
// so handle error here
if(err) return res.status(400).json(message:"Something bad happend");
res.status(200).json({message: 'ok', data:data});
}
// execute the series
async.series([getData, processData, anotherTask], finalHandler);
关于node.js - 在 Node 异步系列 block 中执行不会等待回调触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34928759/