Value arriving late? “Value below was evaluated ju

2019-08-15 04:31发布

问题:

let currComp = this;
let projects = []
let dataArr = []    


async function getData() {
  let getProject =
    await axios.get('url', {
      auth: {
        username: 'username',
        password: 'pw'
      }
    })

  let projects = await getProject.data.value;
  let arr = []
  let KPIs = []

  projects.map(project => {
    let item = () => axios.get(`url`, {
      auth: {
        username: 'username',
        password: 'pw'
      }
    })

    arr.push(item)
    console.log('arr', arr)
  })

  let results = await axios.all(arr)

  results.map(result => {

    result().then(function(v) {
      KPIs.push(v.data.value)
    })
  })

}

getData();

What I am trying to do is:

  1. get an axios call to fetch the name of the projects.

  2. Use those fetched names to call multiple axios calls. This is supposed to give me some data from that project.

  3. results = await axios.all(arr) contains functions that gives me the responses to the API call.

  4. The responses gets pushed in the the array KPIs.

  5. When I try to console.log('KPIs', KPIs) at the end, it gives me

which seems to be an empty array, but when I open it,

it actually has the value that I want.

The problem is, when I try to use this array in my code, it only gives me the first item of the array.

I tried to search this issue online, and it only told me that the value is arriving late.

I want to use the full array with the full result.

How can I fix it?

回答1:

results = await axios.all(arr) contains functions that gives me the responses to the API call.

Yes, but that's pointless. You don't want functions that return promises for responses, and there's no use to call axios.all on array of functions or await that.

You will instead need to build an array of promises, and all() and await that.

You shouldn't need to use then either. You can simplify your code a lot:

async function getData() {
  const getProject = await axios.get('url', {
    auth: {
      username: 'username',
      password: 'pw'
    }
  });

  const projects = getProject.data.value;
  const promises = projects.map(project =>
    axios.get(`url`, {
      auth: {
        username: 'username',
        password: 'pw'
      }
    })
  );

  const results = await axios.all(promises)

  const KPIs = results.map(v => v.data.value);
}