Reputation: 27
I'm confused about synchronous JavaScript vs asynchronous. If by default JavaScript is single threaded and can only complete one operation at a time, line by line, wouldn't this be 'asynchronous' i.e. things do not occur at the same time? How is it synchronous?
Also a piece of async code like a promise, the promise allows the rest of the code to run while it waits to resolve. Wouldn't this be synchronous i.e. letting multiple operations happen at once?
I'm confused as this seems the wrong way round in my mind.
Upvotes: 1
Views: 83
Reputation: 11890
Something can be both single-threaded and asynchronous.
Firstly, let's talk about the difference between a thread and a process.
The basic definition is that separate processes have seperate memory spaces - they can't access each other's memory.
Whereas separate threads share the same memory space.
If we think of a thread as a queue of instructions, a multithreaded application can have two of these queues of instructions operating at the same time, but each accessing the same memory (and potentially screwing up the the state of the memory for the other thread.).
JavaScript is single threaded
All this means is that there is this one queue of instructions.
Now, this does that mean that JavaScript might not be suitable for doing embarrassingly parallel processing like sorting a trillion numbers using the quick sort algorithm, because you can't make use of a computer's multiple processors.
So how does the asynchronous work?
It comes down to the JavaScript event loop, and the fact that JavaScript is non-blocking.
To give an example, if I write some code that looks like:
const response = await fetch("/api/someData");
or not using async/await:
fetch("/api/someData").then(response => {
//Use the response here.
});
And say it takes one second for this response to return, the JavaScript engine doesn't just sit there doing nothing until the reponse returns.
Instead, the event loop continues and it continues processing everything else that it can, until the promise resolves and that code can continue.
If you want more details on exactly how the event loop works, I recommend reading that Mozilla documentation, or this post.
Upvotes: 1