gpt4 book ai didi

javascript - 如何同步 2 个或多个异步请求的数据并使用解析的数据发送响应?

转载 作者:行者123 更新时间:2023-11-30 11:31:57 26 4
gpt4 key购买 nike

举个最简单的例子,假设他们是2个或更多的家伙,需要通过HTTP请求提交数据,其中一个家伙提交的数据必须等待其他家伙发送其他数据到服务器以便被解析。这是我试图在 Node.js 中完成的图像:

enter image description here

解析数据后,需要将其作为响应发回给每个家伙。问题是我坚持执行这个任务(我正在使用 http 模块和长轮询,稍后我将使用 websocket),问题在于回调性质,我尝试使用肮脏的方法,比如制作一个数组填充直到每个人都提交并在 setInterval 函数的帮助下检查是否需要解析数据等。

是否有更简洁、更简洁的方法来执行此类任务?

最佳答案

我会给这个进程一个唯一的 ID(两个客户端都知道),然后将相关数据存储在数据库中或直接存储在服务器 RAM 中。有待处理的请求(请求 - 等待)对服务器不利,因为它必须保持越来越多的开放连接,对客户端不利,因为他看到一个旋转的圆圈而不知道发生了什么。我宁愿做以下事情:

1. client sends request with data
2. data gets stored, a *please wait* is returned
3. the page reloads all two seconds
4. if all the datas there, return the data
5. if not, return *please wait* and goto 3

一个伪实现看起来像这样:

var processes = new Map();

function Process (){
do {
var id = Math floor(Math.random()*10**10);
}while(processes.has(id));
this.id = id;
processes.set(id,this);
}

Process.prototype.pending = function(res){
if(this.first && this.second)
return res.end(this.first + this.second);

res.end(`
<html>
<body>
Please wait...
<script> setTimeout(location.reload.bind(location),2000);
</script>
</body>
</html>`);
};

//the routing
var app = Express();

app.get("/create",function(req,res){
var p = new Process();
req.end(p.id);
});

app.get("/first/:id/:data",function(req,res){
var p = processes.get(req.params.id);
if(!p) return res.end("id not found");
p.first = req.params.data;
p.pending(res);
});

app.get("/second/:id/:data",function(req,res){
var p = processes.get(req.params.id);
if(!p) return res.end("id not found");
p.second = req.params.data;
p.pending(res);
});

关于javascript - 如何同步 2 个或多个异步请求的数据并使用解析的数据发送响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45904690/

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