artemhp
artemhp

Reputation: 1

Puppeteer.Iteration elementHandle array issue

Help me please to achieve the expected result. I am going to fill each input field on the page with a text: '123'.

let inputList = await page.$$('.form input');
inputList.map(async item => {
   await item.type('123');
});

Expected Result - 123 in each field.

Actual Result - 112233 on the last input field.

page.$$(selector) API

Upvotes: 0

Views: 670

Answers (1)

tjc0090
tjc0090

Reputation: 197

In a general sense, you are trying to iterate over an array and perform an asynchronous action on each item in the array. You can accomplish that several ways, the for ... of loop is one way. If you don't want to loop but instead want to iterate you can do it this way:

await inputList.reduce(async (previousVal, currentVal) => {
    await previousVal; // wait for the promise returned by the previous asynchronous call
    return currentVal.type('123'); // call the next elementHandle in the array
}, Promise.resolve()); // the initial value that is passed to the callback function

Upvotes: 1

Related Questions