I have a function that calls an async function to return a response from an API and I need to have it stored in an array. However, when I looked at the content of the array, it does not have the content of the data from the API.
function getDataArray()
{
var arr = [];
getData()
.then(res => arr = res);
return arr; //call goes here without completing the result of the async function
}
async function getData() {
try {
let res = await axios({
url: 'https://jsonplaceholder.typicode.com/posts/1',
method: 'get',
timeout: 8000,
headers: {
'Content-Type': 'application/json',
}
})
if(res.status == 200){
// test for status you want, etc
console.log(res.status)
}
// Don't forget to return something
return res.data
}
catch (err) {
console.error(err);
}
}
I need my getDataArray function to return the array from the async function but am not sure why is the behavior like that even though the function where the axios call to API is made is marked with async.