Author's profile photo

Aylwin's tech blog

Sprinkle a bit of curiosity in everything I do 🧪

Why do we need JavaScript Promises and Async Await

2024-01-20

  • JavaScript Promises and async/await are powerful features that enable developers to handle asynchronous operations in a more organized and readable way. Prior they were introduced, developers need to write a lot of callback functions.
  • The following code will fail because the response object does not exist.

      const axiosRequest = require('axios')
      
      let response = axiosRequest.get("https://www.boredapi.com/api/activity")
      console.log(`You could ${response.data.activity}`)
  • Is there any way for us to get access to the result of the request and run code when it returns?
  • To solve this problem, JavaScript gives us a few ways to wait until a task is finished so we can use the result or catch any error that occur.

      const axiosRequest = require('axios')
      
      axiosRequest
      .get("https://www.boredapi.com/api/activity")
      .then(response => {
          console.log(`You could ${response.data.activity}`)
      ))
      .catch(error => {
          console.error(`ERROR ! ${error}`)
      });
      
      // OUTPUT
      // You could Volunteer at a local animal shelter
    What if there is an error?
      const axiosRequest = require('axios')
      
      axiosRequest
      .get("https://httpstat.is/404")
      .then(response => {
          console.log(`You could ${response.data.activity}`)
      ))
      .catch(error => {
          console.error(`ERROR ! ${error}`)
      });
      
      // OUTPUT
      // ERROR! Error: Request failed with status code 404
  • The examples above introduce a problem where code is not execute sequentially. For example: “Why am I here” is executed first.

      const axiosRequest = require('axios')
      
      axiosRequest
      .get("https://www.boredapi.com/api/activity")
      .then(response => {
          console.log(`You could ${response.data.activity}`)
      ))
      .catch(error => {
          console.error(`ERROR ! ${error}`)
      });
      
      console.log("Why am I here")
  • The await keyword was introduced to solve this problem. According to the mozilla site, the await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.

      const axiosRequest = require('axios')
      
      async function getActivity() {
          let response = await axiosRequest.get("https://www.boredapi.com/api/activity")
      
          console.log(`You could ${response.data.activity}`)
      }
      
      getActivity();
      
      // OUTPUT
      // You could Volunteer at a local animal shelter
    The console log line will not run until the promise resolves or is returned.
  • However, if there is any error occur, we would need to catch the error. Since await allows our code execute sequentially, now we can use try() and catch() block like the following:

      const axiosRequest = require( 'axios')
      
      async function getActivity () {
          try {
              let response = await axiosRequest.get ( 'https://httpstat.us/500')
      
              console. log ('You could ${response data.activity}')
      
          } catch (error)
          {
              console.error ('ERROR: ${error}')
          }
      }
      getActivity ()
      
      // OUTPUT
      // ERROR: Error: Request failed with status code 500

References

Javascript Promises vs Async Await EXPLAINED (in 5 minutes)