[英]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.我正在尝试从我的 vue js 客户端监听 Express 服务器发送的事件。 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:我的 Express 控制器代码是:
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从我的 vue 客户端,我提出了这个请求
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?如何在此处收听服务器立即发送的 Emit? 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.这是
node.js
预期行为,任何同步循环都将始终阻塞线程,循环完成后它将处理其他事件。
Please refer Event loop for more information but for the highlights:请参阅事件循环以获取更多信息,但要了解重点:
There are 5 phases有5个阶段
┌───────────────────────────┐ ┌─>│ 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.现在
poll
是执行同步代码的地方,而pending callbacks
的回调是处理您的回调的地方。 So when the phase moves to poll
it already checked for all the callbacks and async/libuv stuff.因此,当阶段移动到
poll
它已经检查了所有回调和 async/libuv 内容。 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.所以你的
for loop
就在这里,现在直到它完全执行它不会进入事件循环的下一个阶段并返回到pending callbacks
阶段。
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.因此,在循环完成后,它将进入其他阶段,并会看到那里有多个 unservices 回调(您的事件),并且它将一一处理。 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.您可以做的一件事是,您可以分叉另一个进程来为您的事件提供服务并使用
process.send
而不是事件发送fruits
。 Then the process will immediately serve the event handler.然后该过程将立即为事件处理程序提供服务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.