我正在使用nodemon通过nodemon index.js运行我的应用程序

在我的index.js文件中,我使用Puppeteer初始化函数。

索引文件

const dotenv = require("dotenv");
const reddit = require("./reddit");

(async () => {
  // ...
  await reddit.initialize();
  await reddit.login(username, password);
  const results = await reddit.getResults();
  console.log('got results');
})();


这一切都按预期工作。

在我的initialize()函数中,设置了Puppeteer选项

REDDIT.JS

const puppeteer = require("puppeteer");
const fs = require("fs");

const self = {
  browser: null,
  page: null,

  initialize: async () => {
    // Select browser
    self.browser = await puppeteer.launch({
      headless: true,
      slowMo: 10,
      defaultViewport: null
    });
    //  create new page
    self.page = await self.browser.newPage();
  },
};

module.exports = self;


我遇到问题的地方是我的getResults()函数

getResults: async () => {
    // ...
    await self.page.goto(SUBREDDIT_URL(reddit), { waitUntil: "networkidle0" });
    const elements = await self.page.$$(
      '#siteTable > div[class*="thing"]:not(.promoted)'
    );
    const results = [];

    await Promise.all(
      elements.map(async element => {
        // ... logic done that pushes items to results array
      })
    );
    console.log("about to write to file");

    await fs.writeFile(
      `${__dirname}/results.json`,
      JSON.stringify(results),
      err => {
        console.log("currently writing");
        if (err) return false;
        return true;
      }
    );

    console.log("finished writing to file");

    return await Promise.all(results);
}


当我运行它时,我在控制台中得到以下内容

about to write to file
finished writing to file
got results
currently writing


我期待

about to write to file
currently writing
finished writing to file
got results


我的功能在文件写入之前完成的地方哪里出错了?

任何帮助将不胜感激。

最佳答案

fs.writeFile()的常规版本不返回承诺,因此await不执行任何操作。 await仅在您等待诺言时才有用。

最新版本的node.js承诺支持fs模块。您可以这样做:

const fsp = require('fs').promises;

async function someFunc() {
    await fsp.writeFile('someFilename', someData);
    // other code here
}


请注意,我的惯例是将导入的模块命名为fsp而不是fs,以便使其与普通的fs明显不同。

关于javascript - 使用puppeteer来等待fs writefile不会等到文件写入后才继续进行事件循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58086232/

10-16 14:14