Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not a Constructor with async function

Tags:

I am trying to make a constructor function in JavaScript, and this constructor should be asynchronous, cause I am using Phantom JS module to scrape the data,so that's why I have to use asynchronous function to scrap data through Phantom JS with Node JS.

Below is my code,

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

But when I run this code it says, InitScrap() is not a constructor, am I missing something ?

like image 985
Nadeem Ahmad Avatar asked Aug 05 '18 12:08

Nadeem Ahmad


People also ask

Can a constructor be async?

A simple answer for that: No, we can't! Currently, class constructors do not return types, and an asynchronous method should return a Task type.

Which of the following is not a building constructor in JavaScript?

The following JavaScript standard built-in objects are not a constructor: Math , JSON , Symbol , Reflect , Intl , Atomics . Generator functions cannot be used as constructors either.

Can constructor be async in JavaScript?

This can never work. The async keyword allows await to be used in a function marked as async but it also converts that function into a promise generator. So a function marked with async will return a promise. A constructor on the other hand returns the object it is constructing.

Can constructor be async typescript?

Async Option ConstructorThe async function call can be added right into the class instantiation step, without needing a separate init() call or having to modify your established method of class construction.


1 Answers

Constructor functions are functions that return an Object of the type defined in the function, like this "Person" class from MDN you cited:

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

It returns an Object with a name and a greeting function when used with the new keyword.

When you use the async keyword, you can await Promises in the function but it also converts that function into a promise generator, meaning it will return a Promise, not an Object, that's why it can't be a constructor.

like image 63
Luca Kiebel Avatar answered Oct 11 '22 17:10

Luca Kiebel