UnhandledPromiseRejectionWarning:错误:评估失败

时间:2020-01-02 13:02:57

标签: javascript asynchronous async-await puppeteer

我正在尝试使用操纵up和datalayer-puppeteer库来自动化网站上的GTM容器测试。到目前为止,我已经编写了以下简单代码:

const puppeteer = require('puppeteer');
const dataLayer = require('puppeteer-datalayer');

(async () => {

    // Automate here
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    const containerId = "GTM-5LDMPBF";



    await page.goto('https://www.example.com');
    await page.click('#header > nav > div.main-navigation > a');
    const dataLayerPuppeteer = new dataLayer(page, containerId);
    console.log(await dataLayerPuppeteer.history());


    await browser.close(); 
})();

问题是,当我运行它时,出现以下错误: UnhandledPromiseRejectionWarning:错误:评估失败:dataLayer未定义。应该定义dataLayer并使其可见。我应该以某种方式等待该声明,还是有其他解决方法?

2 个答案:

答案 0 :(得分:0)

我只是试图在代码中添加一些try-catch,也许它可以帮助您处理错误

   const puppeteer = require('puppeteer');
const dataLayer = require('puppeteer-datalayer');

(async () => {
    try {
    // Automate here
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    const containerId = "GTM-5LDMPBF";



    await page.goto('https://www.ifortuna.sk');
    await page.click('#header > nav > div.main-navigation > a');
    const dataLayerPuppeteer = new dataLayer(page, containerId);
    console.log(await dataLayerPuppeteer.history());


    await browser.close(); 
    }
    catch (e) {
        console.error(e);
    } finally {
        console.log('We do cleanup here');
    }
})();

答案 1 :(得分:0)

问题是您要单击主导航中的链接。如果您单击该链接,则puppeteer不会等待下一页加载。这意味着您正在尝试在页面仍在加载时读取dataLayer。 如果您删除链接以进行测试,它将起作用:

const puppeteer = require('puppeteer');
const dataLayer = require('puppeteer-datalayer');

(async () => {

    // Automate here
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    const containerId = "GTM-5LDMPBF";

    await page.goto('https://www.ifortuna.sk');
    // await page.click('#header > nav > div.main-navigation > a');

    const dataLayerPuppeteer = new dataLayer(page, containerId);
    console.log(await dataLayerPuppeteer.history);

    await browser.close(); 
})();

另一个小问题:dataLayerPuppeteer.history是一个吸气剂,因此必须写成dataLayerPuppeteer.history而不是dataLayerPuppeteer.history() (文档中没有提及,我将添加它;))