DEV Community

Ali Abbas
Ali Abbas

Posted on

Explain Javascript Async/Sync like I am Five

Sometimes, it's hard to comprehend the difference between the two. So Explain it like I am Five.

Top comments (1)

Collapse
 
sleepyfran profile image
Fran González • Edited

Sync means that the code will be executed one step at a time and you have to wait until the thing you're currently doing finishes before going to the next step. When your code is async you can do multiple things at once, so you don't need to wait until the current thing finishes to go to the next. Consider this example:

const result = aSyncOperation();
console.log(result);
console.log('Onto the next thing!');

And this one:

anAsyncOperation().then(result => console.log(result));
console.log('Onto the next thing!');

If both aSyncOperation and anAsyncOperation return the same result (say, an string or a integer, it doesn't really matter) the first example will print firstly the result and then Onto the next thing! while the second one will print Onto the next thing! and then the result. That's because since the second operation is async your code can continue regardless that operation finished or not.

That's why when you're working with Promises you don't get a value back immediately but rather process it inside the then callback. Async is the way to go when you want to do something that requires a lot of time, like doing network requests or file reading.

JavaScript by itself is always sync, but with Node and some Web APIs you get the illusion that you're doing async things in JavaScript. There's a very good video explaining how this all works: