DEV Community

Cover image for async/await Crash Course
Kumar Abhirup
Kumar Abhirup

Posted on

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.'))
Enter fullscreen mode Exit fullscreen mode

can also be written as

 await promise
 console.log('Done Last.')
Enter fullscreen mode Exit fullscreen mode

Just like in the below snippet. It just works!

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


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

Here are two nice resources about it πŸ”₯


If you spot a mistake, let everyone know πŸ™Œ


About me

I am Kumar Abhirup, a 16-year-old JavaScript React developer from India who keeps learning a new thing every single day.

Connect with me on Twitter 🐦
My personal website and portfolio πŸ–₯️

Comment below your better ways, and suggestions to improve this post.Β :)

Top comments (9)

Collapse
 
jmfayard profile image
Jean-Michel πŸ•΅πŸ»β€β™‚οΈ Fayard • Edited

async/await is a big step forward for JavaScript

It still have a problem common with Promise is that you may launch your promise and forget to "await" or ".then()" it, and then you have still done your side effect but didn't wait for it. Of course you may say that it's the programmer who is stupid for doing a simple mistake, but in my opinion when thousands of programmers do the same mistake, it's the designer of the library that did one.

In Kotlin, coroutines have solved this:

  • suspending functions are awaiting by default, you don't need to await explicitely
  • Flow give you cold asynchronous streams - like in reactive sterams / RxJs / RxJava - while Promise and async/await are hot

GitHub logo Kotlin / kotlinx.coroutines

Library support for Kotlin coroutines

kotlinx.coroutines

official JetBrains project GitHub license Download

Library support for Kotlin coroutines with multiplatform support This is a companion version for Kotlin 1.3.61 release.

suspend fun main() = coroutineScope {
    launch {
       delay(1000)
       println("Kotlin Coroutines World!")
    }
    println("Hello")
}

Play with coroutines online here

Modules

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt

I really love Kotlin for this.

Another easy for Kotlin is generators and yields.

Collapse
 
kumareth profile image
Kumar Abhirup

Nice info! Thanks a lot πŸ˜‹

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

I wonder if "starting with semicolons" is a new standard after ASI and no-semicolon.

But mine is a little different async IIFE.

;(async () => {
  // code
})().catch(console.error)

Other special cases.

;[
  ...
].forEach

;(a as any).key

Also, there is a rule in ESLint called no-return-await, so

async function foo () {
  return await fetch('/api')
}

// is same as

async function foo () {
  return fetch('/api')
}

// is same as

function foo () {
  return fetch('/api')
}

Yes, you can await sync functions as well, as long as it returns a Promise.

Collapse
 
kumareth profile image
Kumar Abhirup

Yes. I have an ESLint rule enforcing those rules... Those are nice!

Collapse
 
gabbersepp profile image
Josef Biehler • Edited

Hi, this line is wrong:
promise.then(console.log('Done Last.'))
It should be
promise.then(() =>console.log('Done Last.'))
:-)

Collapse
 
kumareth profile image
Kumar Abhirup

Thanks for the feedback, will update :)

Collapse
 
ahmadawais profile image
Ahmad Awais ⚑️

Love that theme. πŸ˜‰

Collapse
 
kumareth profile image
Kumar Abhirup

It's urs! And it's awesome!