Async/Await

Introduction to async and await in JavaScript.

Background

We know two ways of writing asynchronous code. Although using promises prevents the “pyramid of doom,” it does not have neat syntax. To make things very clean, we can use Async/Await!

Introduction to async

async token lets you declare a special type of function that always returns a promise. The async functions, unlike normal functions, is much neater when doing asynchronous tasks. Let’s declare an async function.

var func = async function(){
    // Add tasks async or sync
}

The syntax is mostly the same as for a function, except that we prepend the token async before the function keyword.

We can convert anonymous functions into async functions this way.

var func = async () => {
    // Add tasks async or sync
}

The approach is the same for these functions; just prepend async token.

Other than that, these functions always return a promise. See that in the code below.

Get hands-on with 1200+ tech skills courses.