DEV Community

Discussion on: Understanding Asynchronous in javascript

Collapse
 
justmedev profile image
justmedev • Edited

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

function getFromServerSync (uri) {
  console.log("started sync task")

 return /* get data from server (this takes a few seconds)*/;
}

console.log("before call sync")
const res = getFromServerSync("example.com");
console.log("response sync: ", res);
Enter fullscreen mode Exit fullscreen mode

second script

async function getFromServerAsync (uri) {
  console.log("async task started");
  const data = await /* get data from server async */;
  return data;
}

console.log("before call async");
const asyncRes = getFromServerAsync ("example.com");
console.log("response async: ", asyncRes);
Enter fullscreen mode Exit fullscreen mode

Now the first script will log

before call sync
started sync task
response sync: { ... }
Enter fullscreen mode Exit fullscreen mode

and the second one:

before call async
response async: undefined
async task started
Enter fullscreen mode Exit fullscreen mode

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