繁体   English   中英

如何使用从与 NodeJS 的 mysql 连接保存到异步 function 的变量?

[英]How can I use a variable saved from a mysql connection with NodeJS to an asynchronous function?

我正在尝试使用 Puppeteer 抓取网站。 我想 select 插入我的数据库中的最后一个帖子的日期并将其与刮取的日期进行比较,以便我可以查看该帖子是否已经在数据库中(使用日期作为参考来查看它是否已被修改)。

这是我的代码:

const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: '',
    database: 'db_webcrawler_coches'
});

connection.connect((err) => {
    if (err) throw err;
    console.log('Connected!');
});

let lastpublishedDate;
let idCoches;
connection.query("SELECT id_coches, publish_date FROM coches ORDER BY publish_date DESC limit 1", function (err, row) {
    if (err) throw err;
    lastPublishedDate =  row[0].publish_date;
    idCoches = row[0].id_cochesNet;
    console.log("Published in", lastPublishedDate);
    console.log("Id Coches", idCoches);
});

const run = async () => {
    try {
        const options = {
            headless: false,
        };

        ...

            const news = await page.evaluate(() => {
                const idsList =  [...document.querySelectorAll('div.mt-SerpList-item')].map(elem => elem.getAttribute("id")).filter(elem => elem.includes("#"))
                const datePost = [...document.querySelectorAll('span.mt-CardAd-date')].map(elem => elem.innerText);

                    for(let i = 0; i < titlesCar.length; i++){
                        const finalDate = parsedDates[i];
                        if (finalDate > lastPublishedDate || idCoches !== idsList[i]){
                            console.log("Not repeated");

                            const carsList[i] = [
                                idsList[i],
                                parsedDates[i]
                            ]
                        } else {
                            console.log("Repeated")
                        }
                    }
                return carsList;

            });

            ...


  } catch (err) {

        console.log(err);
        await browser.close();
        console.log("Browser Closed");
    }
  };

run();

如您所见,我想查看日期是否相同以及从查询中获取的 id。 但是,出现一个错误,显示评估失败:ReferenceError:变量“lastPublishedDate”未定义,我想它与“idCoches”相同。 我写了一些 console.logs 来查看它何时崩溃,似乎它在到达function "news"时发生。 我不确定是因为它是 scope 还是因为 function。 你认为我应该怎么做才能让它发挥作用?

会不会是 scope? 谢谢!

编辑:解决了! 如果有人遇到类似问题,我会发布它。 确实是 scope,这是与 Puppeteer 相关的问题。 似乎带有 page.evaluate() 的 function 无法在其中获取任何变量。 要更改它,您需要按以下方式添加 page.evaluate: await page.evaluate((variable_1, variable_2) => { /*... */ }, variable_1, variable_2);

当异步 function 运行时,对您的查询的回调可能尚未返回,因此无论您尝试引用什么都没有定义。 我不确定您的 mysql 客户端是否支持承诺,但如果支持,您可以执行以下操作:

const run = async () => {
   const row = await connection.query("SELECT id_coches, publish_date FROM coches ORDER BY publish_date DESC limit 1")
   lastPublishedDate =  row[0].publish_date;
   idCoches = row[0].id_cochesNet;

   ...

}

如果这不起作用,您还可以在查询的回调中运行所有内容。 希望有帮助。

暂无
暂无

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

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