【问题标题】:Execution in a node async series block does not wait for callback to fire节点异步系列块中的执行不等待回调触发
【发布时间】:2016-01-22 01:50:21
【问题描述】:

我需要同步实现一个 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 块不会等到它的回调被调用。相反,执行线程似乎跳出了异步块,并且顶级方法在其结果可用之前返回。:-

  1. getHttp 之前
  2. getHttp 之后
  3. 离开 listObjs,应该在调用下一步之后
  4. 离开 GET /objs API!! []
  5. 现在触发下一个异步步骤
  6. 下一步,处理返回的Objects,result=
  7. 异步块末尾 [{"name":"obj1"},{"name":"obj2"}],2

那么为什么在我的第二阶段执行之前退出 async.series 块? 也就是说,为什么消息 4. 不在我的跟踪消息的末尾?

提前非常感谢

【问题讨论】:

  • 您的列表真的很难与您的代码相关联,您能否将该列表的每个数字注释到您的 sn-p 中的相应区域?

标签: node.js asynchronous


【解决方案1】:

输出是正确的!它们是异步的,它们将在自己的任务完成时执行。这是您的完整代码

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2021-06-30
    • 1970-01-01
    • 2020-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多