简体   繁体   English

来自node.js的多个异步响应

[英]Multiple async response from node.js

I am working on a node.js app where upon login, we need to send lots of information from different entities to user, to fill their dashboard. 我正在开发一个node.js应用程序,该应用程序在登录时需要将来自不同实体的大量信息发送给用户,以填充其仪表板。

So instead of holding the response till we get all the things from the database, I am trying to send chunks of information as they come. 因此,我不等待响应直到我们从数据库中获得所有东西,而是尝试在信息到达时发送信息块。 I believe res.write is the method that I suppose to use. 我相信res.write是我应该使用的方法。

I am using mongoose, so instead of using await for all my queries. 我正在使用猫鼬,所以不是对所有查询都使用await。 I fire them all side by side (in hope of speeding up the process). 我将它们并排解雇(以期加快进程)。

Eventually, I need to end the response, but I don't know how to be sure if everything that I need is being returned(all tasks are completed). 最终,我需要结束响应,但是我不知道如何确定是否返回了我需要的所有内容(所有任务都已完成)。

This type of behaviour cannot be dictated by the server, the server has 1 request from the client and if the server needs to fetch from multiple other resources before completing that request then unfortunately the client will just have to wait. 服务器无法确定这种类型的行为,服务器从客户端收到1个请求,如果服务器需要在完成该请求之前从多个其他资源中获取信息,那么不幸的是,客户端仅需等待。

Alternatively, and this sounds to me like the more appropriate approach, split the calls up into separate APIs and have the client fetch each one independently - this would give you the desired effect of not having to wait for all the data to return before you can start rendering the view. 另外,这听起来更像是一种更合适的方法,将调用分成单独的API,并让客户端独立地获取每个API-这将为您带来预期的效果,无需等待所有数据返回就可以开始渲染视图。

You can use await Promises.all([task1, task2,...]); 您可以使用await Promises.all([task1, task2,...]); if you want to fetch needed information in a single request. 如果您想在单个请求中获取所需的信息。

You can also fire up multiple requests from the dashboard to fetch all the needed information in parts. 您还可以触发来自仪表板的多个请求,以获取零件中所有所需的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM