在单独的 js 文件中从异步函数导出结果,将结果导入另一个 javascript

问题描述

尝试构建一个小型刮板。为了重用功能,我认为“页面对象模型”会派上用场。

在 main.js 中,我需要多个小脚本,在下面的示例中只有一个模型 (GooglePage)。 脚本工作。但我想知道如何将 google.js 脚本中的值传递回主脚本。 我想在 main.js 脚本中使用“pageCountClean”变量的值,以便在应用程序的其余部分中使用。

一直在寻找有关在脚本之间传递值函数的信息。用于从 pageconstructors 导出值,用于 promise await 导出功能。 但我迷路了。我是否必须使用 Promises?,目前的要求/导入和导出方式是否足以创建脚本之间的关系? 欢迎任何指点。

//////////// main.js

const { chromium } = require('playwright');
const { GooglePage } = require('./models/Google');

(async () => {
const browser = await chromium.launch({ headless: true,slowMo: 250 });
const context = await browser.newContext();
const GoogleUrl80 = https://www.google.nl/search?q=site%3Anu.nl;

// Cookie consent:
console.log('Cookie consent - start');
const page80 = await browser.newPage();
await page80.goto('https://google.nl');
await page80.waitForTimeout(1000);
await page80.keyboard.press('Tab');
await page80.keyboard.press('Tab');
await page80.keyboard.press('Enter');
console.log('Cookie Consent - done');

// Number of urls in google.nl (using google.js)
await page80.goto(GoogleUrl80,{waitUntil: 'networkidle'});
const googlePage80 = new GooglePage(page80);
await googlePage80.scrapeGoogle();
// Want to console.log 'pageCountClean' here.

await browser.close()
})()

//////////// Google.js

class GooglePage {
constructor(page) {
  this.page = page;
}

async scrapeGoogle() {
    const GoogleXpath = '//div[@id="result-stats"]';
    const pageCount = await this.page.$eval(GoogleXpath,(el) => el.innerText);
    const pageCountClean = pageCount.split(" ")[1];
    console.log(pageCountClean);
      }
   }
  module.exports = { GooglePage };

解决方法

您可以直接从 pageCountClean 函数返回 async 并在 main.js 文件中await

在 Google.js 中:

async scrapeGoogle() {
    const GoogleXpath = '//div[@id="result-stats"]';
    const pageCount = await this.page.$eval(GoogleXpath,(el) => el.innerText);
    const pageCountClean = pageCount.split(" ")[1];
    console.log(pageCountClean);
    return pageCountClean;
}

在 main.js 中:

const googlePage80 = new GooglePage(page80);
const result = await googlePage80.scrapeGoogle();
console.log(result);