Understanding Async/Await in Javascript | Key Things to Remember

Why use Async/Await?

The reason why I will also prefer async/await is because it makes code so much cleaner and easier to read, especially when you have multiple chaining going on. Readability and maintainability are always on the top of my mind when I am writing code. Your colleague will appreciate your clean code, even if they never mention it!

Key Things to Remember

  • Async/Await is nothing more than syntactic sugar around promises
  • Async functions are functions that return promises
  • Await can only be used inside a function marked async
  • Use try/catch with async functions to catch exceptions

Learn by Example

Personally, one of the best ways for me to learn is through examples. This is why I will keep my explanations short. I am also going to keep my examples super simple and easy to follow.

Simple HTTP Request with Axios

Let’s take a look at a simple function that gets a post from jsonplaceholder using promises.

function getToDo() {
  axios.get('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => console.log(response.data))
    .catch(error => console.error(error))
}

We can rewrite this using async/await like this:

async function getToDo() {
  try {
    const response = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
    console.log(response);
  } catch (error) {
    console.log(error);
  }
}

A More Real-World HTTP Request Example

Here is a snippet from a project I recently worked on. Superagent is lightweight http library similar to Axios. The getCustomer function is making a HTTP request and setting Authorization headers. Once I receive the response, I set them in my data variables (I am using Vue.js as the frontend framework in this project).

import request from 'superagent';

...

const getCustomer = (id) => {
  request
    .get(`${process.env.CUSTOMERS_ENDPOINT}/customer/${id}`)
    .set('Authorization', this.$store.state.idToken)
    .then(response => {
      this.customers = response.body.userProfiles;
      this.page = response.body.currentPage;
      this.maxPages = response.body.totalPages;
    })
    .catch(err => {
      this.$config.showError(err);
    });
}

...

Now let’s rewrite this to use async/await:

import request from 'superagent';

...

const getCustomer = async (id) => {
  try {
    const response = await request
      .get(`${process.env.CUSTOMERS_ENDPOINT}/customer/${id}`)
      .set('Authorization', this.$store.state.idToken)

    this.customers = response.body.userProfiles;
    this.page = response.body.currentPage;
    this.maxPages = response.body.totalPages;    
  } catch (error) {
    this.$config.showError(error);
  }
}

...

Async/Await with a simple MongoDB Request

Here is an example of a database call to MongoDB with Mongoose using promises.

const db = require('../models');

module.exports = {
  findById: function(req, res) {
    const { id } = req.query;
    
    db.Book.find(id)
      .sort({ date: -1 })
      .then(data => res.json(data))
      .catch(err => res.json(err));
  }
};

Async/Await!

const db = require("../models");

module.exports = {
  findAll: async function(req, res) {
    const { id } = req.query;

    try {
      const books = await db.Book.find(id).sort({ date: -1 });
      res.json(books);
    } catch (err) {
      res.json(err);
    }
  }

Conclusion

My intent here is to keep the article short and sweet. Something that people can use as a reference or guide. As previously mentioned, if you are seeking more in-depth explanations regarding the internal workings of Promises and Async/Await, there are tons of great resources that covers this topic. Thank you!

#javascript #nodejs #vue #programming

Understanding Async/Await in Javascript | Key Things to Remember
197.60 GEEK