不是具有异步功能的构造函数

Nad*_*mad 5 javascript node.js phantomjs

我试图在 JavaScript 中创建一个构造函数,这个构造函数应该是异步的,因为我使用 Phantom JS 模块来抓取数据,所以这就是为什么我必须使用异步函数通过 Phantom JS 和 Node JS 来抓取数据。

下面是我的代码,

const phantom = require('phantom');
async function InitScrap() {

  var MAIN_URL = "https://www.google.com/",
      //Phantom JS Variables
      instance = await phantom.create(),
      page = await instance.createPage();


  // Load the Basic Page First      
  this.loadPage = async function() {
    console.log("Loading Please wait...");
    var status = await page.open(MAIN_URL);
    if (status == "success") {
      page.render("new.png");
      console.log("Site has been loaded");
    }
  }

}

var s = new InitScrap();
s.loadPage()

// module.exports = InitScrap();
Run Code Online (Sandbox Code Playgroud)

但是当我运行这段代码时,它说,InitScrap()不是构造函数,我错过了什么吗?

Luc*_*bel 3

构造函数是返回函数中定义类型的对象的函数,就像您引用的 MDN 中的“Person”类一样:

function Person(name) {
  this.name = name;
  this.greeting = function() {
    alert('Hi! I\'m ' + this.name + '.');
  };
}
Run Code Online (Sandbox Code Playgroud)

当与关键字一起使用时,它返回一个带有名称和问候函数的对象new

当您使用async关键字时,您可以await在函数中使用 Promise,但它还会将该函数转换为 Promise 生成器,这意味着它将返回 Promise,而不是 Object,这就是它不能是构造函数的原因。