简体   繁体   中英

How to listen to server(express) sent event from client(vue) instantly

I am trying to listen to Express server sent events from my vue js client. I want to listen to it as soon as it is emitted. But it does not until the whole process is finished.

My Express Controller Code is:

exports.getFruits = (req, res, next) => {
   const fruits = ["mango", "jackfruit", "banana", ...........];
   for(let i = 0; i < fruits.length; i++){
      res.emit('fruit', fruits[i]);
   }
};

From my vue client, I'm making this request

axios.get("localhost:3000/get-fruits")
.then(res => {
   console.log(res.data);
})
.catch(err => {
   console.log(err);
});

How can I listen to the server sent Emit instantly here? Any help would be highly appreciated.

This is expected behaviour of node.js any synchronous loop will always block the thread and after the loop is complete it will process the other events.

Please refer Event loop for more information but for the highlights:

There are 5 phases

 ┌───────────────────────────┐ ┌─>│ timers │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ pending callbacks │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ idle, prepare │ │ └─────────────┬─────────────┘ ┌───────────────┐ │ ┌─────────────┴─────────────┐ │ incoming: │ │ │ poll │<─────┤ connections, │ │ └─────────────┬─────────────┘ │ data, etc. │ │ ┌─────────────┴─────────────┐ └───────────────┘ │ │ check │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ └──┤ close callbacks │ └───────────────────────────┘

Now poll is where synchronous code is executed and pending callbacks are where your callbacks are processed. So when the phase moves to poll it already checked for all the callbacks and async/libuv stuff. So your for loop is here, Now until it is fully executed it wont go to the next phase of the event loop and return to the pending callbacks phase.

So after the loop completes it will go to the other phases and will see that there are multiple unservices callbacks are there (your events) and it will process it one by one. Hope you understood the concept.

One thing you can do is, you can fork another process just to serve your events and send the fruits using process.send rather than events. Then the process will immediately serve the event handler.

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