简体   繁体   English

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

[英]Await is only valid in async function with nodejs

I'm developing a web capture app and it seems that all the functions are with async but console shows me a SyntaxError: await is only valid in async function error.我正在开发一个网络捕获应用程序,似乎所有功能都带有异步功能,但控制台向我显示SyntaxError: await is only valid in async function错误中SyntaxError: await is only valid in async function

I tried to change all the functions to async but it seems still not working.我试图将所有功能更改为异步,但似乎仍然无法正常工作。 Is it an error because of the fs module?是因为 fs 模块的错误吗? I think when I tried without fs module in another app it actually works.我认为当我在另一个应用程序中尝试不使用 fs 模块时,它确实有效。

Here's my full code这是我的完整代码

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();
})();

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

fs.readFile('db.txt', async function (err, data) {}

The answers suggesting to make the callback async will make the error disappear, but the overall readFile operation will not be awaited.建议使回调async的答案将使错误消失,但不会等待整个readFile操作。 So, if for instance, you would enable the line with await browser.close();因此,例如,您可以使用await browser.close();启用该行await browser.close(); , that browser.close() will run before the readFile callback executes. ,该browser.close()将在readFile回调执行之前运行。

When you use promises, you are better off using the Promise API for fs :使用Promise 时,最好使用Promise API for fs

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

const handle = await fs.readFile('db.txt');
const data = await handle.readFile();
let array = data.toString().split("\n");
// ...etc


await handle.close();

This way:这边走:

  • You don't have a callback, and you can use await with the file and other asynchronous operations您没有回调,您可以将await与文件和其他异步操作一起使用
  • The main async function's returned promise will only resolve when all await -tasks have been performed.async函数返回的承诺只有在所有await任务都执行后才会解决。

您必须在回调函数中使用async才能使用await否则您会收到错误消息。

fs.readFile('db.txt', async (err, data) => { });

the callback function inside fs needs to be async as well fs 中的回调函数也需要异步

this part : fs.readFile('db.txt', async function (err, data)这部分: fs.readFile('db.txt', async function (err, data)

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', async 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();
})();

read more here about async-await ' https://javascript.info/async-await在这里阅读更多关于async-await ' https://javascript.info/async-await

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

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