Karthi
Karthi

Reputation: 479

Find matching elements in array using async/await and promise.all

filterdList.length value always equal total number of elements with below code. So this method always returning false. There is only one item in the table that is matching with given name.

async itemExists(name) : Promise<boolean>{
const itemList = await element.all(this.itemList)
const filterdList= await Promise.all(itemList.filter( async (item) =>{
  let text = await item.getText();
  if (text == name) {
    return true;
  }
}));

 return await filterdList.length == 1;
}

calling this method as below

console.log(await itemExists('unique item name'));

Upvotes: 2

Views: 8491

Answers (2)

guest271314
guest271314

Reputation: 1

await is only necessary once within async function

async function itemExists(name) {
  const itemList = await Promise.all(element.all(this.itemList)
                   .map(item => item.getText()));
  const filterdList = itemList.filter(item => text === name);
  return filterdList.length == 1;
}

itemsExists(name).then(bool => console.log(bool));

async function itemExists(name) {
  const itemList = await Promise.all(['unique item name', 'not unique item name'].map(item => Promise.resolve(item)))
  const filterdList = itemList.filter(item => item == name);
  return filterdList.length === 1;
}

itemExists('unique item name').then(bool => console.log(bool));

Upvotes: 3

posit labs
posit labs

Reputation: 9431

This line is all kinds of wrong: return await filterdList.length == 1;

First, it looks like you want to return a Promise, not a boolean. Don't use the await keyword in that statement if that's your goal. Secondly, you can't await a boolean. You can only use await on Promise instances. Instead, you can do something like var list = await filterdList, then you can check the length of list later.

I recommend rebuilding this method from scratch, and test with console.log statements along the way. It will give you a better understanding of what is going wrong, and where. Be especially careful about what you are passing to Promise.all. If it's not an array of Promises, then it's not going to behave correctly.

You should probably not filter the array until all of the Promises have resolved. You can get all of the names, then filter. The line below will output the resolved item names, which you can filter through.

var itemNames = await Promise.all(itemList.map(item => item.getName()))
itemNames.filter(...).length

Upvotes: 2

Related Questions