javascript - How do I know when the last async operation will finish? -
i'm building app in nodejs , involves sending external requests asynchronously. had 1 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 result, when exactly? res.end("ok"); }, function (e) { // error, when exactly? res.end("error"); });
now have array:
# 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; (var id in ids) { anotherserverclient.sendexternalrequest(id), function(data) { //success //return result res.end("ok"); }, function (e) { // error res.end("error"); }); } }
how can know when last operation in loop "for (var id in ids) {" finish return result client after that? what's idiomatic , simple solition?
// server app.post("/dsfdsfd", function (req, res, nxt) { var ids = req.body.ids; // create output array collect responses var output = []; (var id in ids) { anotherserverclient.sendexternalrequest(id, function(data) { // on success, push response output array output.push(data); // check if responses have come back, , handle send // if length of our output same list of requests if(output.length >= ids.length){ //return results array res.end("ok"); } }, function (e) { // if api call fails, send error res.end("error"); }); } });
Comments
Post a Comment