Await仅在带有nodejs的异步函数中有效

问题描述 投票:0回答:1

我正在开发一个Web捕获应用程序,似乎所有功能都具有异步功能,但控制台向我显示了SyntaxError: await is only valid in async function错误。

我试图将所有功能更改为异步,但似乎仍然无法正常工作。是否由于fs模块而出错?我认为当我尝试在另一个应用程序中不使用fs模块时,它实际上可以工作。

这是我的完整代码

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

let galleryName = "frozen"; // Enter gallery name

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  // Adjustments particular to this page to ensure we hit desktop breakpoint.
  page.setViewport({
    width: 1000,
    height: 10000,
    deviceScaleFactor: 1
  });

  fs.readFile('db.txt', function (err, data) {
    if (err) throw err;
    let array = data.toString().split("\n");
    for (i in array) {
      console.log(`Now Processing : ${array[i]} ${array.length - i -1} left`);
      await page.goto(`https://gall.dcinside.com/${galleryName}/${array[i]}`), { // !!!!ERROR shows from here
        waitUntil: "networkidle2",
        timeout: 0
      };
      async function screenshotDOMElement(opts = {}) {
        const padding = "padding" in opts ? opts.padding : 0;
        const path = "path" in opts ? opts.path : null;
        const selector = opts.selector;

        if (!selector) throw Error("Please provide a selector.");

        const rect = await page.evaluate(selector => {
          const element = document.querySelector(selector);
          if (!element) return null;
          const {
            x,
            y,
            width,
            height
          } = element.getBoundingClientRect();
          return {
            left: x,
            top: y,
            width,
            height,
            id: element.id
          };
        }, selector);

        if (!rect)
          throw Error(
            `Could not find element that matches selector: ${selector}.`
          );

        return await page.screenshot({
          path,
          clip: {
            x: rect.left - padding,
            y: rect.top - padding,
            width: rect.width,
            height: rect.height + padding * 2
          }
        });
      }

      await screenshotDOMElement({
        path: `./result/${pageNumArray[i]}.png`,
        selector: ".view_content_wrap",
        padding: 10
      });
    }
  });
  //   // await browser.close();
})();
javascript node.js asynchronous
1个回答
4
投票

fs中的回调函数也需要异步,

fs.readFile('db.txt', async function (err, data) {}
© www.soinside.com 2019 - 2024. All rights reserved.