1

I'm using vuex on a project. on the store I made a function that returns, form an API, the info of all the users from an array of ids. something like this:

async function getUsersdata(userIds){
  let userData = new Array()
  userIds.forEach(async (id) => {
    const url = baseUrl + id + '/'
    const data = await getUserDetails(url)
    userData.push(data)
  })
  return userData 
}
   

later I use this function and when I try to do a foreach on the array that the function returns the forech doesn't work. But if console log the entire array, the array displays correctly

let Users = await getUsersdata(idArray)
console.log(await Users)
Users.forEach(User => console.log(User.name))

also when I try to console log the length of the array it returns undefined or 0, and when I use functions such as .sort() or .map() it doesn't execute either.

0

2 Answers 2

2

Async await doesn't work inside forEach, intead you should use for iterator.

async function getUsersdata(userIds){
  let userData = new Array()
  for(var i=0; i<userIds.length; i++) {
    const id = userIds[i]
    const url = baseUrl + id + '/'
    const data = await getUserDetails(url)
    userData.push(data)
  }
  return userData 
}

Sign up to request clarification or add additional context in comments.

1 Comment

Showing for of here would seem superior and keep code closer to the original. Also something about why.
-2

It's strange, perhaps someone can explain the reason behind, but you can do this:

await getUsersdata(idArray)
   .then(Users => {
       console.log(Users);
       Users.forEach(User => console.log(User.name)); // It works!
   });

Or,

let Users;
await getUsersdata(idArray)
   .then(data => {
       Users = data;
   });
Users.forEach(User => console.log(User.name)); // It works!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.