DEV Community

Discussion on: Async operations in JavaScript

Collapse
 
philnash profile image
Phil Nash

This is a good explanation of the various ways we can work with JavaScript asynchronously.

I would recommend you take a look at your introduction again though. JavaScript may be able to run asynchronous tasks concurrently (seemingly at the same time) but it is not truly parallel. The answers in this Stack Overflow question have some good explanations and diagrams for what that really means.

I was really confused when I started the second paragraph and you said:

JavaScript is a synchronous language

I think you meant:

JavaScript is an asynchronous language

It might help to clear that up!

Thanks again for writing this.

Collapse
 
lexlohr profile image
Alex Lohr

Actually, JavaScript is basically a synchronous, single-threaded language with a few extension to allow events to interrupt this single thread and to run asynchronous code either inside a web worker or the GPU.

Collapse
 
philnash profile image
Phil Nash

Hmm, OK, it's not the language that is specifically asynchronous, just the two most popular platforms (web and Node.js) on which the language runs. But that doesn't mean I'd describe JS as a "synchronous" language.

Events don't interrupt the thread, both the web and Node.js run JavaScript code via an event loop. Both the talk by Philip Roberts linked in the article and this talk by Erin Zimmer do a great job of explaining how that works. There are various asynchronous pieces to JavaScript depending on the platform it runs on and they all take their time on the event loop.

Web Workers are something interesting though. They do actually give browser based JavaScript more threads to run on across more CPUs if you have them available. They are an extension that actually makes JavaScript run in parallel, not just concurrently. There appears to be experimental support for multithreading in Node.js since version 10.5 too. It's exciting times for multithreading JavaScript!

Thread Thread
 
lexlohr profile image
Alex Lohr

We should clarify which version we are talking about. If we are talking about the first implementation of JavaScript, this one was synchronous and events did interrupt the main thread.

That doesn't mean that the language itself is necessarily synchronous, but those async implementations are rather referred to as ECMAscript instead of JavaScript.

Thread Thread
 
philnash profile image
Phil Nash

I think you may be hard pressed to find anyone on this site, or even the web, who writes a post about JavaScript and means the version from Netscape 2 (without explicitly saying so).

Thread Thread
 
lexlohr profile image
Alex Lohr

Still, to the day the main thread runs completely synchronous unless you use events, Promises or async/await either directly or indirectly.

Thread Thread
 
philnash profile image
Phil Nash

Sure, if you only write synchronous code it will only run synchronously. ¯_(ツ)_/¯