CodeNewbie Community

Discussion on: What is the difference between synchronous and asynchronous?

Collapse
gaurang847 profile image
Gaurang • Edited

I'll give an example.

If JavaScript were synchronous, it would've printed 42 to the console (considering the call was successful).
Since it is asynchronous, it calls the get_value_from_DB method but it does not wait till it finishes.
It knows that DB operations rely on network and I/O; which are slow. And hence, it lets the execution of your program move ahead before get_value_from_DB could return a value.
Hence, it prints undefined.

The benefit of this is, that JavaScript is fast. It does not have to wait for slow operations to complete. (Although it might be possible to force JavaScript to do that at times. That's considered a bad practice though).
The disadvantage is that you have to learn how to complete your tasks despite this async behavior.
For example, how do I write the result (be it 42 or -1) of get_value_from_DB to the console?