async/await Crash Course

async/await Crash Course

šŸ”„ Learn async/await (very basics) here šŸ‘‡

When you learn async/await in JavaScript, you quickly fall into words like

  • Synchronous & Asynchronous code
  • Event Loops
  • Promises

These things aren't easy to understand in one go. Complex theories gatekeep beginners. So, we will only learn about practical stuff.


Let us first learn about "Promises"

In the below snippet, what we are intending is to output Done First and then output Done Last.

But the below snippet outputs "Done Last" first.

That is now JavaScript behaves. It does not wait by default.

Code Snippet


To make JavaScript wait for a second

to output Done First

and then print Done Last...

We use Promise constructor.

It accepts a function as the only argument.

The function receives few params. 2 of them being resolve and reject.

Code Snippet

resolve accepts arguments.

These arguments later become the params in the .then() function.

So, the .then() function runs only after the promise is resolved.

Well, don't create a Promise just for a "console.log after setTimeout".

This was just for explanation. šŸ™‚


Now, here's the async/await part.

promise.then(() => console.log("Done Last."))

can also be written as

await promise
console.log("Done Last.")

Just like in the below snippet. It just works!

Await tells JavaScript, "Wait until this is finished, then move to the next line".

Wondering what's the async part in the below snippet?

Code Snippet


The await keyword only happens to work inside an async function.

An async function tells the compiler ahead of time that the function will be returning a Promise and will not have a value resolved right away.

Code Snippet


Links

I hope that gives a basic idea about what async/await is and what it does. :)