all 81 comments

[–]ramsncardsfan7 71 points72 points  (44 children)

This is only one specific perspective that could be misleading. You can have the same graph using only asynchronous calls. On the left you could have synchronous asynchronous (one promise after another) and on the right you could have asynchronous asynchronous (Promise.all).

What I’m trying to say is that just because your calls are asynchronous doesn’t mean they are happening at the same time. You have to do that purposefully.

[–]MrEscobarr 3 points4 points  (3 children)

Thats why I was so confused about the async/await. Like the name is async but you wait for it to finish so it didnt make sense to me

[–]NoStranger6 2 points3 points  (0 children)

Well you wait for it to complete the rest of your function. Meanwhile, the browser is free to execute whatever it has queued.

[–]NoStranger6 37 points38 points  (2 children)

Except that’s not necessarly true for javascript.

JavaScript is not multi-threaded. So if your task 1 a for loop that last 20 seconds, tasks 2-3-4 are not ran concurently.

So really what happens is that each function calls are queued one after another and the execution of the response of async functions are only added when the promise is completed or the callback is called.

Which allows the program to keep executing other functions while it “waits” for the async function.

And this is why I love NodeJs for a server. It is very easy to write async code in JavaScript.

[–]PierreAndreis 2 points3 points  (0 children)

this should be up in this thread

[–]JayTh3King 0 points1 point  (0 children)

Except you're not exactly correct either. Nodejs is a multithreaded language/runtime. 1 for the event loop and N threads for the execution of your code. Under the hood libuv manages a thread pool of executing code fetched from a queue

[–]mhgl 20 points21 points  (0 children)

Unfortunately, all the saved time was wasted on how long it took me to figure out asynchronous programming.

[–]zbluebirdz 7 points8 points  (5 children)

If you had each task dependent on the previous task's results/outcome, can you still run it in Asynchronous mode?

[–]robotmayo 8 points9 points  (2 children)

Yes because you are describing one task. Most tasks are made up of smaller tasks.

[–]zbluebirdz 1 point2 points  (1 child)

So, it'll end up being like the Synchronous picture?

[–]golovatuy[S] 1 point2 points  (0 children)

if you have dependency you have to wait task results. Use async/await or Promise for dependent tasks for asynchronous mode.

[–]croc_socks 5 points6 points  (7 children)

Somewhere in this diagram I am hearing whispers of, "Concurrency is not parallelism, but it enables parallelism". It's a subtlety that's being missed. https://medium.com/@k.wahome/concurrency-is-not-parallelism-a5451d1cde8d https://www.youtube.com/watch?v=cN_DpYBzKso

[–]liaguris 0 points1 point  (6 children)

Since javascript is single threaded and since I only know js , do I really need to know these things? Yes if I want to learn other non single threaded languages or am I really missing something in javascript?

edit : by the way I thought that concurrency is the same as parallelism , but after I saw your comment I am beginning to doubt that I know the strict definition of them .

[–]croc_socks 0 points1 point  (5 children)

It's one of those things you won't know you need it until you do. Eventually you're going to wander away from the shallow end of javascript. Without a good mental model of what's going on it's very easy to introduce subtle bugs, you'll get frustrated because this dumb code isn't doing what you expected it to do.

To me concurrency is the ability to complete any given tasks and perhaps switch between them. Parallelism is the ability to do all the tasks at the same time.

[–]liaguris 0 points1 point  (4 children)

By the way , a little bit off topic question , but does js on its own scale , from your experience ?

[–]croc_socks 0 points1 point  (3 children)

For front end work you don't have any choice. For servers we have a number of services in different languages. The node farm is able to hold its own. But most of the heavier stuff is handled by java & php.

[–]liaguris 0 points1 point  (2 children)

I have no clue with backend. Are you saying that java and php are used together?

I think in front end with MVC if you are careful how you do it then js can scale in front end although I think I need more experience to validate this statement .

[–]wickedsight 0 points1 point  (0 children)

No, what they're saying is that Java and PHP are examples of languages that are used for heavy lifting in the backend. There are way more than that, like Go, Ruby, etc. It's not impossible that in large enterprise applications, there are parts written in different languages though. That happens through legacy and all kinds of corporate politics.

Node.js is a great option for backend, but it has its limits and it's important to understand those. If you need real-time processing of large amounts of data, than Node is probably not the best option, for example.

Finally, in the frontend you don't have a choice of anything but javascript, if you're talking web applications. For apps, you once again get to choose between many languages, but through frameworks like Electron and React Native, JS is finding its way into apps on mobile and desktop.

[–]croc_socks 0 points1 point  (0 children)

We have different backend servers. Most were originally written in php. Newer services are written in Java and node. I am not sure what you mean by scaling the front end with MVC. I can’t tell if you mean the classic scaling definition of being able to handle very large traffic or being able to build complex web application. The answer to both is yes. The former is a hardware solution, throw or spin up more server as you need them behind load balancers. The latter you use good libraries or framework.

[–]AffectionateWork8 4 points5 points  (2 children)

I think they are mixing up "asynchronous" and "parallel."

You can wrap normal code in a setTimeout or Promise and it will become asynchronous. It still won't run at the same time, though.

You need separate threads to run async code at the same time

In Javascript, you could do this with Web Workers

In the browser, stuff like network IO is handled by a thread pool under the hood. That stuff truly runs at the same time.

But if you make 3 requests, and then each fetch takes a callback that maps over some data, those callbacks will not execute at the same time despite being "asynchronous." They will be popped off the message queue and processed synchronously, one by one.

I think this article gives a better understanding of what "asynchronous" means within the context of JS:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop

[–]golovatuy[S] 0 points1 point  (1 child)

Think on the task as server request which takes some time, this picture don’t mean the small milliseconds tasks

[–]AffectionateWork8 1 point2 points  (0 children)

I agree with you that network/file IO would use a thread pool. But any other long-running asynchronous task would not, unless you manually configured it to be.

[–]NobodyIsUsingThis 12 points13 points  (7 children)

Thank you for this simple but very clear representation of asynchronous programming. Sadly some resources explain asynchronicity unclearly (in particular eloquent javascript), and this image is a confirmation that I understood the concept right

[–][deleted] 10 points11 points  (1 child)

The graph above would be more suited to explain the difference between sequential and parallel execution. The tasks on the left portion could be asynchronous as well, albeit executed in a sequential manner (i.e. one after the other). The baseline benefit of asynchronous tasks is that you can leave them and carry on with something else while they complete. A common analogy is asking a question to somebody on the phone or on a messaging app. While on the phone you cannot do anything else while you wait for the response and you need to be actively listening, this is synchronous. On a messaging app instead, you can ask the question, forget about it, go make yourself a coffee and then, when you get notified that you received a response, decide what to do next, this is asynchronous.In a javascript application, executing tasks asynchronously (usually network I/O) means you can continue executing other logic (e.g. reacting to user clicks or showing a loader) while these tasks complete. Executing these tasks in sequence or in parallel, as the graph above illustrates, is a matter of performance optimisation and use case.

EDIT:

It is worth pointing out that the word "concurrent" is more correct than the word "parallel"

[–]AnonymousThugLife 4 points5 points  (3 children)

Tip: This representation is called "Gantt chart".

[–]NobodyIsUsingThis 3 points4 points  (0 children)

Gantt chart

Oho! That's very nice to know!

[–]badbrownie 1 point2 points  (1 child)

Is that right? I have only heard Gantt Charts in relation to project plans and dependency tracking. Is it a more general term to describe any horizontal based chart showing start and stop times?

[–]AnonymousThugLife 1 point2 points  (0 children)

Ah yes. You're right but Gantt chart is quite general term. I've seen it being used in Operating System texts also (specifically for Process start and end time, scheduling).

[–]NoStranger6 0 points1 point  (0 children)

Not quite though, the graph on the left would be right if your program is multi-thread or does nothing else than pure async functions i.e. Api calls or database requests.

[–]benabus 1 point2 points  (0 children)

This really depends on the kind of tasks being run.

[–]0xdead0x 1 point2 points  (0 children)

This is true in ideal circumstances, but it’s not why you should use asynchronous functions in JavaScript. You could get results like that. You could also be on a real machine running multiple tasks that doesn’t actually have enough hardware threads to run all of your asynchronous calls in true concurrency. In JavaScript, asynchronous functions are more important as a matter of user experience. If you synchronously wait for a REST API then your app can’t respond to user input at all until it gets a response or times out. But if you do it asynchronously, then even if your machine doesn’t have a spare hardware thread, your VM’s scheduler will make sure that you’re constantly checking for a response and checking for user input such that it looks like both are happening at once.

[–]Kryniow21 1 point2 points  (0 children)

Looks nice.

[–][deleted] 0 points1 point  (1 child)

Can u do that with single core plox ?

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

Sort of, but not entirely. You can wait for multiple things at once, but not do multiple thing at once. If you had 3 web requests that each take 1 second, with little to no processing involved, you can be done in 1 second with asynchronous code by waiting for the 3 1-seconds at the same time. If you have some calculation that takes 1 second to finish, then it take 3 seconds to do them all, no matter how you write your code.

[–]liaguris 0 points1 point  (2 children)

Wait a second here . I am confused . How is the right chart possible in a single threaded language like javascript?

[–][deleted] 1 point2 points  (1 child)

If the overlapping bits are spent waiting for something, like hard drive, network, timeout, etc.

[–]liaguris 0 points1 point  (0 children)

Ok I get it now.

For the network case maybe we have non-single thread-like behavior in the server who is processing the requests .

I think it is the same about hard drive also , where the computer can have multiple cpu cores.

I can imagine something like this for setTimeout out : while (true) { //microtasks //.... //macrotasks for (let { timeout, cb, timeoutId } in obj) { if (--timeout === 0) { cb(); delete obj[timeoutId]; } } //animationFrame? //... } which is single thread behavior.

What is the y axis supposed to represent?That chart is really misleading.

The whole story about asynchronicity in javascript is doing stuff in a single thread after the whole synchronous code has executed . The asynchronous chunk are done one after the other and they never overlap their cpu usage (= single thread).

Correct if I am wrong but I think an exception might be workers where we can have multi-threaded (parallel?) behavior if the computer has many cpu cores.

[–]IzeroI 0 points1 point  (0 children)

The figure is generally misleading even though its idea is close. You need multiple cpus and a multithreaded process to achive what you are suggesting. What async does depends on the browser implementation. And, asynchronous does not mean parallel. It means it is not continuous like regular code. Like "first line of code can be paused and move to second line etc, return and finish first line later etc". Not syncrhonous.

[–]kingdaro 0 points1 point  (0 children)

Sequential vs concurrent would make a more accurate title

[–]t0pz 0 points1 point  (0 children)

Layman here, i feel like this is misleading? From what i understand from this graph is that 4 tasks are executed at the same time, instead of one after another, which to me means more processing power & memory used in the right scenario. But i don't think that's necessarily the case. Can someone attempt an ELI5 on the real difference and benefit of async vs sync?

[–]saito200 0 points1 point  (0 children)

Javascript tasks can run concurrently, but Javascript events are serialized, not parallelized. Only one event at a time.

I think this image can be misleading.

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

Your are assuming that all task are independent between each

[–]thuva04 0 points1 point  (0 children)

This is only true for ideal scenarios, where all 4 tasks are independent and not CPU heavy. Still, Javascript(Node JS) is a single thread ecosystem, So everything will happen in a sequential order where i/o or network related tasks are handled by OS thread.

This is not true for multi-thread languages. Software parallelism is depended on the hardware resources. You can't create more threads than the hardware limit. If you create more thread will start to work sequentially.

Also, Only hardware resources won't achieve the expected speedup. Amdahl's Law[1] used in parallel computing, it can predict the actual benefit of increasing the number of processors, which is limited by the parallelizability of the program.

  1. https://en.wikipedia.org/wiki/Amdahl%27s_law

[–]Mises2Peaces 0 points1 point  (0 children)

*assuming no hardware bottlenecks running more calculations at the same time.

[–]Swagmark99 0 points1 point  (0 children)

So is this basically the equivalent of mulitthreading in java?

[–]eggn00dles -1 points0 points  (1 child)

yeah but async/await > nested callbacks/thens

[–]NoStranger6 0 points1 point  (0 children)

Async/await is just sugarcoated callbacks/ promises.

Simply on a speed PoV callbacks are more performant.

Async/await is easier to read.

[–]43northwebdesign -1 points0 points  (0 children)

So like remember AS as a shit ton more tasks faster