Image for post
Image for post
Introduction to Async-Await in Javascript

Introduction to Async-Await in Javascript

Vivek Maskara
Sep 30, 2018 · 2 min read

Today I learned that Javascript has a special syntax for working with promises in a more comfortable fashion. It's the async and await which was originally introduced in C#. I am not an expert in Javascript but am quite excited to share the basics about async and await.

Async

async before a function means that the function always returns a promise. If the code has a non-promise return type then Javascript automatically wraps it into a resolved promise with that value.

Let's see how a normal promise looks in javascript.

Here’s a simple example of a function with async keyword.

Executing the above function gives the following result.

Image for post
Image for post
Executing the Async function

Read more about Async function here.

Await

await makes Javascript wait until that promise settles and returns its result. It can only be used inside an async function. The promise could either resolve or get rejected and accordingly the following happens:

  • The execution of the async function continues once the promise is resolved and the value of the await expression is that of the fulfilled promise.
  • If the promise is rejected, the await expression throws the rejected value.

Here’s an example of await in a function.

This is how the output looks:

Image for post
Image for post
Response for a function that uses await

Note: You cannot use await in a normal function. It can be used only in an async function.

Read more about Await keyword here.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store