0

I would like to get the key information in my for await...of loop:

for await (const user of users) {
  const userData= await fetchUserData(user.id)
}

But I get the error .for is not iterable when I do it like this:

for await (const [key, user] of users) {
  console.log(`fetching user ${key} out of ${users.length} users`)
  const userData= await fetchUserData(user.id)
}

Is there a way to get the information about key in my loop ?

Relisora
  • 1,049
  • 1
  • 12
  • 29
  • 3
    what is `users`? – ASDFGerte Apr 13 '21 at 12:04
  • 1
    If `users` is an object it can't be mapped. For retrieve `[key, value]` tupple, you should map `Object.entries` – Hagai Harari Apr 13 '21 at 12:05
  • 1
    It can't be an object, it needs to at least be async iterable – ASDFGerte Apr 13 '21 at 12:06
  • `users` is an array of objects – Relisora Apr 13 '21 at 12:07
  • 2
    If it is an array of objects, why do you use `for await` at all? If you just want the index in a `for ... of` loop over an array, you may want to check e.g. [access-to-es6-array-element-index-inside-for-of-loop](https://stackoverflow.com/questions/34348937/access-to-es6-array-element-index-inside-for-of-loop) – ASDFGerte Apr 13 '21 at 12:08
  • The first code example works very well, my goal with getting the key was to know at which iteration I'm at to have a visual hint during the process – Relisora Apr 13 '21 at 12:12
  • The link fixes my issue with `.entries()`, you can post it as an answer if you want – Relisora Apr 13 '21 at 12:14
  • 1
    `for await` can iterate sync iterables as well, so it "works", but the reason this isn't directly closed as dupe of above question is imho, because the `for await` implies async iterables, where a "key" (or index) doesn't even need to exist. – ASDFGerte Apr 13 '21 at 12:14

1 Answers1

0

for await...of works like for of and needs to specify .entries() to get the key like this:

for await (const [key, user] of users.entries()) {
  console.log(index, value);
}
Relisora
  • 1,049
  • 1
  • 12
  • 29