我正在 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/