1

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.

Joseph
  • 47
  • 8

2 Answers2

3

You should make getDataArray as an async function as well. In your codebase (witout async), return arr will be executed while the getData() method is still being called.

async function getDataArray()
{
    var arr = [];

    arr = await getData()

    return arr; //call goes here without completing the result of the async function
}
wangdev87
  • 8,611
  • 3
  • 8
  • 31
0

call goes here without completing the result of the async function

You're right, getData is asynchronous and will update the arr after it get response from API. You need to make getDataArray asynchronous as it should wait for response.

async function getDataArray() {
  try {
    const arr = await getData()
    return arr
  } catch(err) {
     console.log('Uncaught err ', err)
  }
}

OR

function getDataArray() {
   return new Promise((resolve, reject) => {
      getData().then((response) => {
         // Map response // if any
         resolve(response)
      }).catch(reject)
   })
}
Naren
  • 4,152
  • 3
  • 17
  • 28