send multiple responses to client via nodejs

前端 未结 1 1704
情深已故
情深已故 2021-01-23 15:33

i am using nodejs and i want to send back multiple responses to client.And my code is below

//addwork

var agenda = require(\'../../schedules/job-schedule         


        
相关标签:
1条回答
  • 2021-01-23 16:02

    A http request only gets a single http response. Using http, you only get one response. Some options for you:

    1) Wait for everything to finish before replying. Make sure each part creates a result, success or failure, and send the multiple responses at once. You would need some control flow library such as async or Promises to make sure everything responded at the same time. A good choice if all parts will happen "quickly", not good if your user is waiting "too long" for a response. (Those terms were in quotes, because they are application dependent).

    2) Create some scheme where the first response tells how many other responses to wait for. Then you'd have a different HTTP request asking for the first additional message, and when that returns to your client, ask for the second additional message, and so on. This is a lot of coordination though, as you'd have to cache responses, or even try again if they were not done yet. Using a memory cache like redis (or similar) could fulfill the need to holding responses until ready, with a non-existent meaning 'not ready'

    3) Use an eventing protocol, such as WebSockets, that can push messages from the server. This is a good choice, especially if you don't know how long some events would occur after the trigger. (You would not want to stall a HTTP request for tens of seconds waiting for 3 parts to complete - user will get bored, or quit, or re-submit.). Definitely check out the Primus library for this option. It can even serve the client-side script, which makes integration quick and easy.

    0 讨论(0)
提交回复
热议问题