【问题标题】:Puppeteer.Iteration elementHandle array issuePuppeteer.Iteration elementHandle 数组问题
【发布时间】:2018-03-08 03:20:47
【问题描述】:

请帮助我达到预期的结果。 我将用文本填充页面上的每个输入字段:'123'。

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

预期结果 - 每个字段 123 个。

实际结果 - 最后一个输入字段上的 112233。

page.$$(selector) API

【问题讨论】:

  • 您可能不希望item.type 调用并行运行,因此不要使用map,而是使用for … of 循环,其中await 会停止迭代。
  • @Bergi 谢谢! for ... of 适用于我的情况:-)
  • 看起来您不应该一直使用map,因为您不想生成新数组。
  • @Bergi 好的!感谢您的指导。

标签: javascript async-await puppeteer


【解决方案1】:

一般来说,您正在尝试遍历数组并对数组中的每个项目执行异步操作。您可以通过多种方式完成此操作,for ... of 循环是一种方式。如果您不想循环但想迭代,您可以这样做:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多