JavaScript Await | Async Await in Javascript Tutorial By WDH

JavaScript Await


In plain English,

  • We use async to return a promise.
  • We use await to wait and handle a promise.

Let's expand it further to understand the concepts better.

  • The async keyword is for a function that is supposed to perform an asynchronous operation. It means the function may be taking a while before it finishes execution, returns a result, or throw an error.

    We use the async keyword with a function as,

    COPY

    async function fetchUserDetails(userId) {
        // pretend we make an asynchronous call
       // and return the user details
       return {'name': 'Robin', 'likes': ['toys', 'pizzas']};
    }
    

    With the arrow function,

    COPY

    const fetchUserDetails = async (userId) => {
       // pretend we make an asynchronous call
      // and return the user details
      return {'name': 'Robin', 'likes': ['toys', 'pizzas']};
    }
    

    So, what does the async function fetchUserDetails returns when we invoke it? It returns a Promise.

    async-retuns.png

    The difference between a regular function and an async function is, the latter always returns a promise. If you do not return a promise explicitly from an async function, JavaScript automatically wraps the value in a Promise and returns it.

  • The await keyword is for making the JavaScript function execution wait until a promise is settled(either resolved or rejected) and value/error is returned/thrown. As the fetchUserDetails async function returns a promise, let us handle it using the await keyword.

    COPY

    const user = await fetchUserDetails();
    console.log(user)
    

    Now, you will see the returned user object in the console log,

    await-result

    You would have used the plain-old .then() method to handle that promise without the await keyword.

    COPY

    fetchUserDetails().then((user) => console.log(user));