JavaScript Async & Await: A Complete Guide

JavaScript Async & Await: A Complete Guide

JavaScript promises were a revelation in JavaScript, providing an alternative to the JavaScript callback hell we’d quickly found ourselves in. Async/await functions, a new addition with ES2017 (ES8) for simplifying promise handling. Let's have a look at async and await!

JavaScript promises were a revelation in JavaScript, providing an alternative to the JavaScript callback hell we’d quickly found ourselves in. Promises also allowed us to introduce and better handle asynchronous tasks. While promises were an improvement over callback hell, they still require lots of thens which can become messy. I've really taken to ES2017's async and await keywords for simplifying promise handling. Let's have a look at async and await!

Quick Basics

  • async is a keyword for the function declaration
  • await is used during the promise handling
  • await must be used within an async function, though Chrome now supports "top level" await
  • async functions return a promise, regardless of what the return value is within the function
  • async/await and promises are essentially the same under the hood
  • Available now in most browsers as well as Node.js

Image for post

Benefits of async and await

  • Your code is more simplistic, precise
  • Debugging is easier thanks to fewer callbacks
  • Conversion from promise then / catch code is easy
  • Your code can be more “top-down”, less nesting

Basic async and await Illustration

It’s always easiest to learn from an example, so let’s have a look at a very simple async / await usage

// Function declared as async so await can be used
async function fetchContent() {
  // Instead of using fetch().then, use await
  let content = await fetch('/');
  let text = await content.text();

  // Inside the async function text is the request body
  console.log(text);

  // Resolve this async function with the text
  return text;
}

// Use the async function
var promise = fetchContent().then(...);

Start by declaring the function as async; this declaration allows await to be used from within. The asynchronous routine (fetch in this case) runs and execution of further code halts (though not blocking) until the async action finishes. The function then resolves with the return value and a promise is returned.

Essentially you get to keep your code “inline” without the need for callbacks. It’s async made a bit more simple!

Converting Promise Handling to await

There’s a good chance you’ll want to update your promise code when time becomes available. Let’s walk through updating promise to await:

// Before: callback city!
fetch('/users.json')
  .then(response => response.json())
  .then(json => {
    console.log(json);
  })
  .catch(e => { console.log('error!'); })// After: no more callbacks!
async function getJson() {
  try {
    let response = await fetch('/users.json');
    let json = await response.json();
    console.log(json);
  }
  catch(e) {
    console.log('Error!', e);
  }
}

The conversion from loads of thens to await is simple to execute and your code hopefully looks a bit maintainable!

javascript web-development programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

What Garbage Collection in JavaScript Is and How It Works

JavaScript values are allocated when things are created (objects, Strings, etc.) and freed automatically when they are no longer used. This process is called Garbage collection.

What Javascript Spread Operator is, How It Works and How to Use It

JavaScript spread operator is one of the more popular features that were introduced in ES6. This tutorial will help you understand it. You will learn what spread operator is and how it works. You will also learn how to use it to copy and merge arrays and object literals, insert data and more.

Top 10 Web Development Trends in 2020 | Web Development Skills

Top 10 Web Development Trends in 2020 will provide you with a detailed list of the trends which are currently being noticed. Upskilling to these trends will help you in landing onto better jobs in 2020-2021.