NO! you have not learned wrong that JavaScript is a single threaded language. It is a single-threaded language it has access to a single main thread to execute the code. So when we talk about synchronous programming, we are talking about this lone thread doing all the heavy lifting and executing our code.
But in reality V8 engine and Node.js use a c library called libuv to get access to six extra threads. Two of these are used for doing garbage collection and the rest are used for doing background tasks like asynchronous programming.
Yes. When we say that code is asynchronous or non-blocking what really happens is the async code is passed to these extra threads with the callback and the main thread keeps on doing its work without blocking the rest of the code.
When the async code is finished, the callback function is pushed into the event queue with either error or the required data. Then the event loop pushes it into the call stack and boom we get our result, to understand this with some code. Let's look at the readfile method of fs module.
fs.readFile("demo.text","utf8",(err,data)=>{ if(error){ return error } console.log("output",data); })
In the code above the readfile method is passed to the background threads. The reading to happens in the background, and when that gets finished the callback is pushed into the event queue with either error or data.
Once in callstack the callback is executed and we are left with either error or the data as output.
Thanks for reading I hope I was able to explain about the single threaded means in Javascript.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3