繁体   English   中英

如何在我的代码中的 for 循环中使用“async”或“await”?

[英]How to use "async" or "await" inside for-loop in my code?

我正在尝试开发一种工具,使用“puppeteer”从/向网站收集和发布数据,我写了两个模块,一个是从 JSON 文件中读取 URLS,另一个是 for-loop,其中包括来自另一个访问模块的 function网站并废弃数据。

当我构建函数并运行代码时,我的 PC 第一次挂起,无法确定问题所在,直到我看到解释 NodeJS 中“async”“await”帖子,我试图了解如何将它应用于我的代码,但我不能。

所以我正在尝试通过循环访问网站,然后废弃数据,在我从第一个元素完成后,它应该 go 到循环中的下一个元素,而不是一次执行所有元素,这使得 PC悬挂。

getUrlsAndVisitWebsite.js

const puppeteer = require('puppeteer')
const fs = require('fs');
var visitWebsite= require('/home/projtect1/visitWebsite.js');

async function getUrlsAndVisitWebsite(){
    
  fs.readFile("/home/project1/urls.json", "utf8", (err, jsonString) => {
    if (err) {
      console.log("File read failed:", err);
      return;
      }

  var jsonOBj= JSON.parse(jsonString);
  
  for  (let i = 0; i < 2; i++) {
    var postPath = JSON.parse(jsonOBj[i]).url;
 
    // here I'm using puppeteer to visit websites and scrab data
    visitWebsite(postPath)
    }
  });
}

getUrlsAndVisitWebsite()

访问网站.js

const puppeteer = require('puppeteer')
var fs = require('fs');

async function visitWebsite(postPath){
    const browser = await puppeteer.launch({ 
        headless: false,
        waitUntil: 'networkidle2'
        
     })

    
    const page = await browser.newPage()
    await page.setViewport({ width: 0, height: 0});

    //Loading Cookie from file
    const cookiesString = await fs.readFileSync('./cookies.json');
    
    const Writecookies = JSON.parse(cookiesString);
    await page.setCookie(...Writecookies);

    // GO to the target URL for post 
    console.log(postPath)
    await page.goto(postPath)
    //Wait for the selector that list the elements
    await page.waitForSelector('#gridPostListing');

}

module.exports=visitWebsite;

您的 visitWebsite function 是异步的,您需要在 getUrlsAndVisitWebsite 中等待它。 就像现在一样,它只返回 promise,因此挂起。

只需在您的 visitWebsite 调用之前添加 await 。

暂无
暂无

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

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