简体   繁体   中英

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.

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.

I am using mongoose, so instead of using await for all my queries. 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.

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.

You can use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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