等待异步事件,然后继续等待

时间:2020-09-11 20:02:44

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

我正在与操纵up的人合作,这是我要解决的抽象概念:

从一组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)完成异步方法之后再进行下一次迭代?

谢谢。

1 个答案:

答案 0 :(得分:-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);
        }
    });
})