Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Simplifying a for loop to find an item in an array (returned asynchronously) by condition in JavaScript

I have a function called getItems that returns an array of objects asynchronously. Each object has a isOccupied method that returns a boolean. I wrote a function that takes an index and returns whether index-th item in the array’s isOccupied is true or false.

async itemIsOccupied(index) {
 return getItems().then(items => {
   if (items.length - 1 < index) return false;
   return items[index].isOccupied()
 });
}

This just works fine, but the fact that I have to use an async function to fetch the array makes it lengthy. Is there a way to simplify this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I’d clean it up a little like this…

async itemIsOccupied(index) {
  const items = await getItems();
  return index < items.length && items[index].isOccupied();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading