Dawn17
Dawn17

Reputation: 8297

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?

Upvotes: 1

Views: 37

Answers (1)

danh
danh

Reputation: 62676

I'd clean it up a little like this...

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

Upvotes: 2

Related Questions