Let's me explain with a simple example:
console.log('First log');
console.log('Second log');
console.log('Third log');
As we can see, every line of code will waits for previous line to complete execution before execute next line. this is called with synchronous.
Here another example:
console.log('First log');
setTimeout(()=>{
console.log('Second log');
},2000)
console.log('Third log')
setTimeout function will wait for milisecond time that set in second argument and executes anonymous function in the first arguments
First log
Third log
undefined
Second log
As we can see, Third log does not wait for Second log to execute, the method of not waiting for the previous code to complete is called asynchronous.
When we need asynchronous ?
The best way to use asynchronous is when your website working with server to fetching data or getting response, instead of waiting all data from server fully loaded that maybe takes more than one minutes (depend on speed of your internet and server speed to resolve request) you could use asynchronous to make sure that code ahead will execute and javascript will not waiting server response to complete.
Top comments (4)
I agree with mukul 1312. Recently I had an interview where the first line was a setTimeout and second Line was a promise.resolve
I have not researched completely the topic but seems to be related how JavaScript works with task queue and microtask queue
The explanation that I gave in that moment was the details mentioned here in this post.
Althought the examples of your "async code" are generally correct, you're showing just the tip of the iceberg. You aren't showing "real" async code (await xy) and explain how it works and behaves.
True. It's Will be great if you Explain async along with promises
A simplification of async code is, that it is non-blocking. Meaning when you run async code, that for example gets data from a server, or in node, writes a file, the code doesn't stop the execution of other events.
if you would have code like this
first script
second script
Now the first script will log
and the second one:
in the second part, as you can see, the console.log inside the async function got called after the code that was below the function call.
Why is this?
Because JavaScript queues async task and then executes them at the end. That way, they dont make your website unresponsive while they are working.
Async code is usually used when a task will take longer than a few miliseconds like requesting data from a server or uploading a file to a server.
This example is very simplified, keep that in mind!
Have fun coding