Search code examples
javascriptecmascript-6es6-promise

Save Async/Await response on a variable


I am trying to understand async calls using async/await and try/catch.

In the example below, how can I save my successful response to a variable that can be utilized throughout the rest of the code?

const axios = require('axios');
const users = 'http://localhost:3000/users';

const asyncExample = async () =>{
    try {
        const data = await axios(users);
        console.log(data); //200
    }
    catch (err) {
        console.log(err);
    }
};

//Save response on a variable
const globalData = asyncExample(); 
console.log(globalData) //Promise { <pending> }

Solution

  • 1: Return something from your asyncExample function

    const asyncExample = async () => {
      const result = await axios(users)
    
      return result
    }
    

    2: Call that function and handle its returned Promise:

    The ;(async... is an IFFE (Immediately-Invoked Function Expression). You need it to perform top-level await. It's not part of this answer so don't get confused.

    ;(async () => {
      const users = await asyncExample()
      console.log(users)
    })()
    

    Here's why should you handle it like this:

    • You can't do top-level await (there's a proposal for it though); await must exist within an async function.

    Update late 2024:

    The above isnt true anymore; ESM supports top-level await and has been for quite sometime. So, if you're new to the language, skip I'd suggest to skip these crappy wor karounds (which is exactly what they are) and use ESM instead.

    However I must point out that your original example doesn't need async/await at all; Since axios already returns a Promise you can simply do:

    const asyncExample = () => {
      return axios(users)
    }
    
    const users = await asyncExample()