我如何知道上次异步操作何时完成?

时间:2016-03-07 06:55:28

标签: javascript node.js express asynchronous

我在NodeJs中构建应用程序,它涉及异步发送外部请求。以前我有一个id:

# client
function sendAjax(id) {
$.ajax({
  type: "POST",
  url: "/fsfdsfd",
  data: JSON.stringify({"id": id}),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
}).done(function (data) {
    //.....


# server
app.post("/dsfdsfd", function (req, res, nxt) {
  var id = req.body.id;
  anotherServerClient.sendExternalRequest(id), function(data) {
    //success

    //return the result, but when exactly?
    res.end("ok");
  }, function (e) {

    // error, but when exactly?
    res.end("error");
  });

现在我有一个数组:

# client
function sendAjax(ids) {
$.ajax({
  type: "POST",
  url: "/fsfdsfd",
  data: JSON.stringify({"ids": ids}),
  contentType: "application/json; charset=utf-8",
  dataType: "json",
}).done(function (data) {
    //.....


# server
app.post("/dsfdsfd", function (req, res, nxt) {
  var ids = req.body.ids;
  for (var id in ids) {
    anotherServerClient.sendExternalRequest(id), function(data) {
      //success

      //return the result
      res.end("ok");
    }, function (e) {
      // error
      res.end("error");
    });
  }
}

我怎么知道循环中的最后一个操作" for(var id in ids){"将结束 之后才将结果返回给客户端?什么是惯用和简单的解决方案?

2 个答案:

答案 0 :(得分:1)

// server
app.post("/dsfdsfd", function (req, res, nxt) {
  var ids = req.body.ids;
  // create output array to collect responses
  var output = [];
  for (var id in ids) {
    anotherServerClient.sendExternalRequest(id, function(data) {
      // on success, push the response to the output array
      output.push(data);
      // check if all responses have come back, and handle send
      // if the length of our output is the same as the list of requests
      if(output.length >= ids.length){
        //return the results array
        res.end("ok");
      }
    }, function (e) {
      // if any api call fails, just send an error back immediately
      res.end("error");
    });
  }
});

答案 1 :(得分:0)

有几种方法可以做到这一点,所有这些都是惯用的,而且与个人品味有关。

有一个名为async的库可以为这些操作提供帮助。它特别包含用于遍历集合并执行与每个项异步的方法。查看forEachOfforEachOfSeriesforEachOfLimit了解详情。

您可以实现此using Promises。让您的API返回Promises而不是接受回调。然后创建一个Promises数组,每个调用一个,然后使用Promise.all等待所有它们。

ES6规范现在包含Promise,这表明将来最喜欢的方式。