javascript - 我如何知道最后一个异步操作何时完成?

标签 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) {”中的最后一个操作何时完成 之后才将结果返回给客户端?惯用且简单的解决方案是什么?

最佳答案

// 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");
    });
  }
});

关于javascript - 我如何知道最后一个异步操作何时完成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35837850/

相关文章:

javascript - Flask 中的动态散列链接

javascript - 如何使用粒子使用 HTML5 <canvas>

javascript - 在 Node.js 套接字中写入和 'data' 事件

node.js - Nodejs/Express 中的 HTTP 响应完全是乱码

javascript - 我的nodejs代码出错

javascript - 网络音频API : Prevent microphone input from being played through speakers

javascript - 如何根据数据事件属性激活 jQuery UI Accordion?

javascript - 从变量javascript创建变量

node.js - Jade(PUG) 到 Handlebars,加载 SVG 图像的辅助功能问题

javascript - Node.js 应用程序在本地正常工作,但在 Droplet Ubuntu 上出现 404 错误