gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 07:30:08 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com