DEV Community

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

Collapse
 
mebble profile image
Neil Syiemlieh

I'll try to keep this short. I hope the basic idea will still get through though.

First, promises. Normally, you'd have some data in your code, which is assigned a variable name. That variable is just sitting there and you can do whatever you want to it, pass it to a function, print it to the console, etc. No limitations.

But what if you have the variable name, but the data that should be in it isn't available yet? What if that data will be available in the future? Well now, if you print the variable to the console, it might not show up! The data might be available much later, after you've issued the print command. This is where promises come in.

A promise is a box, a "safe space" where you can be sure the data will available. Inside this box, the data will be available and you can do whatever you want to that data. Outside this box, it isn't safe. The data isn't guaranteed to be available.

There's one special feature though. If you've got data inside a box that's within another box, simply opening the outer box will reveal to you the data. So you don't have to go through the burden of opening two boxes. It does it automatically for you! If this has confused you, you can forget this paragraph.

Now for the main bit. You can open the box, do whatever you want to the data, and close up the box again. That's what .then (opening the box) and the return within the .then callback (closing it up again) do in promises. Notice here that we don't actually take the data out of the box. It's not safe to do that. We just do stuff to it, and then close the box back up.

The async/await are just cleaner ways of doing the exact same thing. An async function is basically a "safe open space" where you can open up a box, be sure the data would be available in it and actually take out the data! The await is you opening up the box and taking out the data. So it's a .then with more freedom.

When you write

const unBoxed = await myPromise;

inside an async function, myPromise is the box that holds the future data, and unBoxed will hold that data when it is available. It's all gonna be safe since we're in our async safe space. At the end of the async function, when you return data to the outside unsafe world, the async function will automatically wrap that data up in a box to keep it safe. Hence, the return value of an async function is a promise.

Why do we need this safe space? This safe space is "the future". Code within this space will execute in the future. So it's obvious that we don't want it mixing with code that's gonna execute right now.

Collapse
 
rupeshiya profile image
Rupesh Krishna Jha

thanks a lot @neil