Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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> }
like image 589
Jonca33 Avatar asked Jan 18 '18 17:01

Jonca33


People also ask

How do you use async await in a variable?

The await keyword is used to get a value from a function where you would normally use . then() . Instead of calling . then() after the asynchronous function, you would simply assign a variable to the result using await .

How does async function return a value?

To return values from async functions using async-await from function with JavaScript, we return the resolve value of the promise. const getData = async () => { return await axios.

Does await need to return a value?

Await expressions make promise-returning functions behave as though they're synchronous by suspending execution until the returned promise is fulfilled or rejected. The resolved value of the promise is treated as the return value of the await expression.

Does await stop execution?

Description. The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment.


2 Answers

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:

;(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.

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()
like image 100
nicholaswmin Avatar answered Oct 24 '22 03:10

nicholaswmin


try..catch creates a new block scope. Use let to define data before try..catch instead of const, return data from asyncExample function call

(async() => {

  const users = 123;

  const asyncExample = async() => {
    let data;
    try {
      data = await Promise.resolve(users);
    } catch (err) {
      console.log(err);
    }
    return data;
  };

  //Save response on a variable
  const globalData = await asyncExample();
  console.log(globalData);
  // return globalData;
})();
like image 37
guest271314 Avatar answered Oct 24 '22 03:10

guest271314