简体   繁体   English

如何同步打开页面列表

[英]How to open list of pages synchronously

let downloadPageLinks = [];
fetchStreamingLinks.forEach(async (item) => {
    page = await browser.newPage();
    await page.goto(item, { waitUntil: "networkidle0" });
    const fetchDownloadPageLinks = await page.evaluate(() => {
        return loc4;
    });

    console.log(fetchDownloadPageLinks);
});

I have an array of links( fetchStreamingLinks ).我有一个链接数组( fetchStreamingLinks )。 Above function opens all the links simultaneously present in fetchDownloadPageLinks .上面的 function 打开所有同时存在于fetchDownloadPageLinks中的链接。 Suppose the array contains 100 links then it opens all the 100 links simultaneously.假设数组包含 100 个链接,那么它会同时打开所有 100 个链接。

Now what I want to do is, open all the links one by one present in fetchStreamingLinks , perform some logic in page context's and close it then open next link.现在我想做的是,一一打开fetchStreamingLinks中的所有链接,在页面上下文中执行一些逻辑并关闭它,然后打开下一个链接。

.forEach() is not promise-aware so when you pass it an async callback, it doesn't pay any attention to the promise that it returns. .forEach()不支持承诺,因此当您向其传递async回调时,它不会关注它返回的 promise。 Thus, it runs all your operations in parallel.因此,它并行运行您的所有操作。 .forEach() should be essentially considered obsolete these days, especially for asynchronous operations because a plain for loop gives you so much more control and is promise-aware (eg the loop will pause for an await ). .forEach()这些天基本上应该被认为是过时的,尤其是对于异步操作,因为一个普通for循环给你更多的控制并且是 promise-aware (例如循环将暂停await )。

let downloadPageLinks = [];
for (let item of fetchStreamingLinks) {
    let page = await browser.newPage();
    await page.goto(item, { waitUntil: "networkidle0" });
    const fetchDownloadPageLinks = await page.evaluate(() => {
        return loc4;
    });
    await page.close();
    console.log(fetchDownloadPageLinks);
}

FYI, I don't know the puppeteer API really well, but you probably should close the page (as I show) when you're done with it to avoid pages stacking up as you process.仅供参考,我不太了解 puppeteer API,但您可能应该在完成后关闭页面(如我所示)以避免在处理时页面堆积。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM