Array not iterable when returned by an async function in JavaScript

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.

34 thoughts on “Array not iterable when returned by an async function in JavaScript”

  1. 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 
    }
    
    
    Reply

Leave a Comment