View profile

Why JavaScript's Event Loop is Better than Threads

I'm sure you've heard that JavaScript is single threaded. That is true, but thinking about JavaScript
Why JavaScript's Event Loop is Better than Threads
By Mastering JavaScript Tutorials • Issue #13 • View online
I’m sure you’ve heard that JavaScript is single threaded. That is true, but thinking about JavaScript in terms of threads is missing the point.
For example, even though JavaScript is “single threaded”, it is still possible to start an HTTP server and make an HTTP request to that server in the same process. In fact, it is much easier to do so in JavaScript than in a threaded language, because you would need a separate thread for your HTTP server and a separate thread for the request.
The event loop behaves like a queue of event handlers. Every time you `await` on a promise, you are effectively yielding the main thread back to JavaScript’s event loop, but you also register an event handler that tells JavaScript to resume your function when the promise is settled.
The event loop then processes any other event handlers, and, when the promise you’re awaiting on is settled, your function picks up where it left off. For example, if you implement an async sleep function in JavaScript, your `await` “yields” the main thread back to the event loop, but registers an event handler that resumes the function after 2 seconds. In the meantime, JavaScript can run other functions.
This concurrency strategy is good enough for most web applications. That’s because most web applications don’t do much heavy computation, they spend most of their compute time waiting for network requests. REST APIs don’t store data, they usually defer that work to a database. Browser apps typically make requests to APIs and render the results, but the actual compute time spent rendering versus waiting for HTTP requests is typically small.
Threads are great for optimizing CPU usage for applications that do heavy calculations. But JavaScript apps typically aren’t CPU bound. And even if you have a long-running synchronous calculation in JavaScript, you can use `await` or generator functions to avoid blocking the main thread.

This Week's Tutorials
Did you enjoy this issue?
Mastering JavaScript Tutorials

Mastering JavaScript Tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue