DEV Community

Discussion on: Explain async and await of Javascript like I am five.

Collapse
 
pdlozano profile image
David Lozano

Might be a little late but I'll try.

You are going to an event. But before you do that, you must first put your clothes on. For simplicity, let's just say you'll wear the following:

  1. A shirt
  2. A pair of jeans
  3. A pair of socks
  4. A pair of shoes

Let's try to codify those as functions:

function putShirtOn() {}
function putJeansOn() {}
function putSocksOn() {}
function putShoesOn() {}
Enter fullscreen mode Exit fullscreen mode

Now, if you were to write synchronous code, the program would follow the flow from top to bottom. In other words, if you told your program to putShirtOn(), putJeansOn(), putSocksOn(), and putShoesOn(), it will do so in that EXACT order - even if there's no reason to.

You see, there's no reason why you can't put your jeans on before your shirt - and vice versa. So why not do both at the same time?

That's asynchronous programming.

Here's a visual courtesy of Cambridge Intelligence:

Visual comparing async vs sync

Now for await. You see, you can't put your shoes on without putting your socks on first. If you did, you'd have to remove your shoes back again to put the socks in.

This is where await comes in - it tells the function to really just wait for the data to come or for a function to finish before executing everything else.

Collapse
 
rupeshiya profile image
Rupesh Krishna Jha

thanks for this awesome answer @david