Lets See Server Side Code First.
io.on('connection', (socket) => {
socket.on('message', async () =>{
await sleep(10000); //This Function Takes 10s To Process
console.log( total)
})
});
Client Side
socket.on('connect', () => {
console.log('connected!');
for(var i=0;i < 100000; i ){
socket.emit('message', 'room1');
}
});
Here I am trying to spam my server. Now Every Request Should Take 10s, But Here Only First Emit consumes 10 second and then every requests gets executed instantly.
Please Explain This Nature Of Event And Async-Await.
Thanks :)
CodePudding user response:
This happens because Node.js is async.
What you did on the client is send 100000 messages almost at the same time, so the Node.js server receives all of these messages one by one and Socket.io calls your callback, in your callback you are doing sleep
that I assume is just a wrapped setTimeout
, so this particular callback waits for setTimeout
to be executed, but here when Eventloop comes into play, while this callback waiting for the setTimeout
other JS code is executed, so all of these 100000 messages are processed, and each of the callback waits for the setTimeout
. So as a result after 10 seconds setTimeout
callback will be called by the EventLoop, and then your code will be executed.
It can confuse you if you are used to working with e.g. Java, where each client has a dedicated process/thread, and hence sleep
would block the whole proccess from execution.
You can read more about the event loop here https://nodejs.dev/learn/the-nodejs-event-loop
UPD: You can see when your callbacks are actually called by means of adding a simple console.log
before calling the sleep
function.