Reputation: 3493
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> }
Upvotes: 58
Views: 148220
Reputation: 22959
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:
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()
Upvotes: 64
Reputation: 39
I had same issue with you and found this post. After 2 days of trying I finally found a simple solution.
According to the document of JS, an async
function will only return a Promise
object instead of value. To access the response of Promise
, you have to use .then()
method or await
which can return the resulting object of Promise is instead of Promise itself.
To change variables from await
, you have access and change the variable you want to assign within the async function instead of return from it.
//Save response on a variable
var globalData;
const asyncExample = async () =>{
try {
const data = await axios(users);
globalData = data; // this will change globalData
console.log(data); //200
}
catch (err) {
console.log(err);
}
};
asyncExample();
But if you do this, you may get an undefined output.
asyncExample();
console.log(globalData) //undefined
Since asyncExample()
is an async
function, when console.log
is called, asyncExample()
has not finished yet, so globalData
is still not assigned. The following code will call console.log
after asyncExample()
was done.
const show = async () => {
await asyncExample();
console.log(globalData);
}
show();
Upvotes: -1
Reputation: 318
Just use a callback/promise (cascading programming):
axios(users).then(function(response) {
const globalData = response;
console.log(globalData)
});
Upvotes: -4
Reputation: 1
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;
})();
Upvotes: 6
Reputation: 4821
Because the events are happening asynchronously you need to tie in a callback/promise. I'm going to assume it returns a promise.
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().then( (success, err) => {
if (err) { console.error(err); }
console.log(success)
}
Upvotes: -3