簡體   English   中英

帶有 puppeteer 的 await fs writefile 不會等到文件寫入后再繼續事件循環

[英]await fs writefile with puppeteer doesn't wait until file has written before continuing event loop

我正在使用nodemon通過nodemon index.js運行我的應用程序

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

索引.JS

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() function 中,我設置了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() function

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

我的 function 在文件寫入之前完成,我在哪里出錯了?

任何幫助將不勝感激。

fs.writeFile()的常規版本不返回 promise ,因此await什么也不做。 如果您正在等待 promise,則await只會做一些有用的事情。

node.js 的最新版本具有對 fs 模塊的 promise 支持。 你可以這樣做:

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

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

請注意,我的慣例是命名導入的模塊fsp而不是fs ,以使其更明顯不同於普通的fs

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM