loading...
Cover image for async/await Crash Course

async/await Crash Course

kumar_abhirup profile image Kumar Abhirup ・2 min read

πŸ”₯ 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!

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.Β :)

Posted on by:

kumar_abhirup profile

Kumar Abhirup

@kumar_abhirup

I am a 16-year-old JavaScript React developer from India who keeps learning a new thing every single day. 😍 Twitter: @kumar_abhirup Website: kumar.now.sh

Discussion

pic
Editor guide
 

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

 

I really love Kotlin for this.

Another easy for Kotlin is generators and yields.

 

Nice info! Thanks a lot πŸ˜‹

 

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.

 

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

 

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

 

Thanks for the feedback, will update :)

 

Love that theme. πŸ˜‰

 

It's urs! And it's awesome!