Manvinder
Manvinder

Reputation: 4591

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).

Upvotes: 0

Views: 61

Answers (2)

abskmj
abskmj

Reputation: 758

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.

Upvotes: 0

James
James

Reputation: 82136

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.

Upvotes: 1

Related Questions