Ad

Await Inside For Loop And Break For Loop If Condition Matched

I have an array. I need to iterate on array until data not found. once data found, I need to break for loop and just return those data.

const arrayData = ['1', '2', '3']

for (let i = 0; i < arrayData.length; i++) {
  data = await getSomeDataFromDB(arrayData[i]) // get data from DB
  if (data.length >= 1) { break } // If found break for loop else iterate again
}
return { items: data }

I have used the above code. Is this right way or any other better way to handle this kind of scenario?

Appreciate your help!

Ad

Answer

You could omit the implicit global vairable by just returning from the loop:

for (const entry of arrayData) {
   const items = await getSomeDataFromDB(entry) // get data from DB
   if (items.length >= 1) 
      return { items };
}
Ad
source: stackoverflow.com
Ad