简体   繁体   English

如何检测Promise.all的结束

[英]How to detect the end of Promise.all

I am trying to get a response when all the promises are complete, every promise is a diferent process of web scraping.我试图在所有承诺完成后得到回应,每个 promise 都是 web 抓取的不同过程。 This is the output that I get for the following code as you can see all finished is the first output how to get in the end?这是我得到的output下面的代码你可以看到全部完成的是第一个output到底怎么弄?

all finished
partial end
partial end
partial end

Code in NodeJs using puppeteer使用 puppeteer 在 NodeJs 中编写代码

const puppeteer = require("puppeteer");
const URLs = [
    'https://www.google.es/search?q=dog&sxsrf=ALiCzsaZ5RIpFrQHMAxy9uZ9vbCu2wDAlw:1662240805949&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjp7ZPGyfn5AhVEgv0HHSbDC1oQ_AUoAXoECAIQAw&biw=1280&bih=576&dpr=2',
    'https://www.google.es/search?q=dog&sxsrf=ALiCzsaZ5RIpFrQHMAxy9uZ9vbCu2wDAlw:1662240805949&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjp7ZPGyfn5AhVEgv0HHSbDC1oQ_AUoAXoECAIQAw&biw=1280&bih=576&dpr=2',
    'https://www.google.es/search?q=dog&sxsrf=ALiCzsaZ5RIpFrQHMAxy9uZ9vbCu2wDAlw:1662240805949&source=lnms&tbm=isch&sa=X&ved=2ahUKEwjp7ZPGyfn5AhVEgv0HHSbDC1oQ_AUoAXoECAIQAw&biw=1280&bih=576&dpr=2'
];

main();

async function main() {
    await scrapingUrls().then(console.log("all finished"));
}

async function scrapingUrls() {
    const prom = [];
    for (var i = 0; i < URLs.length; i++) {
      prom.push(scrapInformation(URLs[i]));
    }
    return await Promise.all([prom]);
}

function scrapInformation(url) {
    return new Promise(async function(resolve, reject) {
      const browser = await puppeteer.launch()
      const page = await browser.newPage()
  
      await page.goto(url, {waitUntil: 'networkidle2'});
      
      await browser.close().then(function () {
        console.log('partial end');
        resolve();
      })
    });
  }

This:这个:

 await scrapingUrls().then(console.log("all finished"));

is wrong.是错的。 You should give a function to.then():你应该给.then()一个function:

await scrapingUrls().then(() => console.log("all finished"));

Here the console.log("all finished") is executed right away.在这里, console.log("all finished")立即执行。

Also:还:

 return await Promise.all([prom]);

just prom without the brackets.只是没有括号的prom

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

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