【问题标题】:Wait for an asyncronus event before continue in a for await在继续等待之前等待异步事件
【发布时间】:2020-09-13 19:57:58
【问题描述】:

我正在与 puppeteer 合作,这是我想要解决的抽象概念:

从一组 URL 中,找到所有图像并获取 BoxModel

// URLS, easy step
const urls = ['google.com', 'amazon.com', 'github.com', 'so on'];

// This is basically a browser tab from chromiumn a.k.a. puppeteer
const page = const page = (await browser.pages())[0];

// Add magic function

magic1(page) // all those listen from different page events
magic2(page)
magic3(page)
imageMagic(page) // this one wait for 'load' event


// inside imageMagic function

    page.on('load', async function () { // wait untill load to find images
        try {
            const imgs = await page.$$('img');
            for await (const itm of imgs) {
                // DO things with each image
            }
        } catch (e) {
            console.error(e);
        }
    });

那么主要的过程就在下面:

async function ultraPowerMagicFunction(url){
      try {
        await magic(page)
        await magic2(page)
        await magic3(page)
        await imageMagic(page)
    
        const navigate = page.waitForNavigation({
          waitUntil: 'load',
        });
    
        await page.goto(url);
    
        await navigate;

        // Here I need to wait until imageMagic finish
        // nextExecution()
      } catch (e){
        console.error('PROBLEM IN MAIN FLOW:', e);
      }
}

现在作为最后一步,我需要为每个项目执行此操作

for await (cont url of urls) {
   await ultraPowerMagicFunction(url);
}

在简历中,如何等到事件触发 (load) 完成他们的异步方法后再进行下一次迭代?

提前致谢。

【问题讨论】:

  • await once(page, 'load') 应该在现代 nodejs 中使用。
  • 是的,但我需要在加载过程中等待下一步。
  • “等待加载进程”是什么意思?您只是在等待加载,现在开始处理。
  • 这是做网页剪贴,“加载”是页面已经加载的时候,就像任何网页上的DOM一样。但是每次迭代我都必须更改请求的 URL,然后迭代中的每个项目都有一个“加载事件”

标签: javascript node.js asynchronous async-await puppeteer


【解决方案1】:

您可以使用 Promise 构造函数,以便异步函数在完成时发出信号:

return new Promise((res, rej) => {
    page.on('load', async function () { // wait untill load to find images
        try {
            const imgs = await page.$$('img');
            for await (const itm of imgs) {
                // DO things with each image
            }
            res();
        } catch (e) {
            rej(e);
        }
    });
})

【讨论】:

猜你喜欢
  • 2017-11-14
  • 1970-01-01
  • 2021-07-12
  • 1970-01-01
  • 2018-04-19
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多