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
functiongetFromServerSync(uri){console.log("started sync task")return/* get data from server (this takes a few seconds)*/;}console.log("before call sync")constres=getFromServerSync("example.com");console.log("response sync: ",res);
second script
asyncfunctiongetFromServerAsync(uri){console.log("async task started");constdata=await/* get data from server async */;returndata;}console.log("before call async");constasyncRes=getFromServerAsync("example.com");console.log("response async: ",asyncRes);
Now the first script will log
before call sync
started sync task
response sync: { ... }
and the second one:
before call async
response async: undefined
async task started
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
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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