在 Javascript 中导入异步函数

Importing async functions in Javascript

我是 Node、Javascript 和 Puppeteer 的初学者。给定以下代码,其中我只是尝试使用来自不同文件的一个函数:

const waitForFrame = require ("../../lib/frames");
const screenshotFolder = 'test/screenshots';

module.exports = async(page) => {

    try {
      const iframe = await waitForFrame(page);
      await iframe.waitForSelector('.competition-response__copy');
      await page.waitForSelector({
        visible: '.competition-response__copy'
      });

      const confirmationMessageText = await frame.$eval('.competition-response__copy > p', e => e.textContent);
      return confirmationMessageText;

    } catch (err) {
      await page.screenshot({
        path: screenshotFolder + '/saveYourEntryButton.png',
        fullPage: true
      });
    }

还有一个名为:

的帮助文件

module.exports = async function waitForFrame(page) { export async 
function waitForFrame(page) {
  let fulfill;
  const promise = new Promise(x => fulfill = x);
  checkFrame();
  return promise;

  function checkFrame() {
    const frame = page.frames().find(f => f.name() === 'iframe');
    if (frame) {
      fulfill(frame)
    } else
      page.once('frameattached', checkFrame);
  }
};

而我的包裹json如下:

"engines": {
  "node": ">=6"
},
"dependencies": {
  "chai": "^4.1.2",
  "chai-as-promised": "^7.1.1",
  "lodash": "^4.17.10",
  "mocha": "^5.2.0",
  "puppeteer": "^1.6.2",
  "yargs": "^12.0.1",
  "express": "^4.16.4",
  "supertest": "^3.3.0"
},
"devDependencies": {
  "chai": "^4.2.0",
  "chai-dom": "^1.8.1",
  "mocha": "^5.2.0",
  "js-comments": "^0.5.4",
  "chai-as-promised": "^7.1.1",
  "express": "^4.16.4",
  "supertest": "^3.3.0",
}
}

我收到如下错误:

import {waitForFrame} from "../../lib/frames";
       ^

SyntaxError: Unexpected token {
    at new Script (vm.js:79:7)

我确定这是初学者的错误,但感谢您的快速指导。我知道有许多不同的导入方法,具体取决于您也遵守的 Javascript 标准。

谢谢

您正在尝试将 import 用作本机,但这是 no still supported on ES6,问题与异步函数无关,而是作为意外标记导入,您有一些替代方案:

  1. 不要使用 importexport 而是使用:

    const waitForFrame = require("../../lib/frames");

这很好用,在 Node 6 中受支持。

  1. 迁移到节点 10,在那个 version is supported 中您可以使用它。

  2. 使用编译器,例如 babel 或任何其他适合您的编译器,这涉及更多的依赖项,但您可以在最旧的 Node 版本上使用现代 API。

一切都取决于你喜欢什么。

希望对您有所帮助!