2

The data engineer in my team wrote a program to pull data from a certain API, and, well... it doesn't work. I've been tasked with fixing it, so I've been going through and now I'm trying to figure out what this chunk of code does.

async function asyncForEach(array, callback) {
  const isArray = Array.isArray(array)
  for (const key in array) {
    if (isArray ? key < array.length : array.hasOwnProperty(key)) {
      const val = array[key]
      await callback(val, key)
    }
  }
}

It seems like it checks if an item is an array, and then something do do with the value of the array key...?

eathren
  • 83
  • 7
  • look like a helper function, the forEach array method but it's asynchronous, for each element of a array do the callback function but asynchronously. e.g. `asyncForEach([0, 1, 2, 3], d=>{return d*2;})` returns a `Promise` – Andrew Allen May 08 '19 at 14:45

1 Answers1

2

A for..in loop will iterate over the properties of an object. Array indices (array[0], array[1], etc.) are also just object properties. When iterating over the properties of an object, you usually want to check hasOwnProperty to avoid iterating over methods and other properties from the object's prototype, and only iterate over the "actual values on the object itself."

So, this loop appears to combine iterating over both arrays and objects; if it's an array, it checks whether the property/index is < array.length, otherwise it does the customary hasOwnProperty check.

I would say that you shouldn't do this, first and foremost because you should know whether you're dealing with an object or an array, and secondly because this combined use is confusing at best (Q.E.D. by this question).

Also see Why is using "for...in" with array iteration a bad idea?.

deceze
  • 510,633
  • 85
  • 743
  • 889