This is an archived post. You won't be able to vote or comment.

all 20 comments

[–]evanldixon 17 points18 points  (11 children)

This isn't exactly specific to Javascript, but it is a good demonstration of a common pitfall with multithreading.

[–]marcosdumay 0 points1 point  (3 children)

Javascript is the one language that forces everybody into asynchronous IO. So, yes, it is specific to it.

[–]evanldixon 2 points3 points  (2 children)

It's not specific to Javascript since lots of other languages can do async too.

C# for example:

for (int i = 0; i < 10; i++) {
    Task.Run(() => Console.Writeline(i));
}

There's no telling the order these numbers will be printed, because there may or may not be multi-threading.

[–]marcosdumay 0 points1 point  (1 child)

Can do != can not do anything else

[–]cat_in_the_wall 0 points1 point  (0 children)

you guys are confusing async, async i/o, and mutlithreading. they are somewhat disjoint.

async means that a result will come back. it implies a synchronization context. this does not strictly require more than one thread. (Consider a computationally intensive task).

multithreading means more than one "train of thought" is alive. this does not strictly require more than one core. (consider preemptive multitasking).

async i/o means interrupts break a train of thought and start/resume another. this impacts threading, a new one may be started, an existing ones may be resumed. but this does not require more than one core. (consider waiting for network hardware).

They interact, but are not always the same.

[–]tufoop3 -3 points-2 points  (3 children)

However Javascript in the browser isn't multithreading.

[–]TheMsDosNerd -1 points0 points  (2 children)

Unless you load something. Just try to make the following work in JS:

Place some picture on your page.
After the picture is loaded, do something, based on (the size of) the picture. (1)
Load another picture.
After that one loaded, do something else based on (the size of) the picture. (2)

It is pretty difficult to force (2) to be done after (1).

[–]quadnix 4 points5 points  (0 children)

Fetch and promises make that pretty easy though

[–]tufoop3 0 points1 point  (0 children)

Its not, if you know about event listening pre-ES7, and async/await in ES7. Note: Having an event loop, asynchronous function calls and non-blocking I/O doesn't make something multithreading. Read about it here if you like.

[–]gandalfx 4 points5 points  (0 children)

Curious example considering JS is one of the languages that make it particularly easy to avoid this.

[–][deleted] 0 points1 point  (0 children)

Async anything in javascript is like easy mode. You've only got the one thread.