i am asking if it is possible i could use Puppeteer in class methods. I read a lot about async/await functions but i could not find anything regarding classes. I currently have this:
class Tools{
async login() {
this.browser = ppt.launch({
headless: true,
});
this.page = this.browser.newPage();
this.page.type('#email','test');
...
}
Main method:
(async function main() {
try {
const tools = await new Tools();
} catch(e) {
console.log('Error: ' + e);
}
})();
Any advice on this?
You are just calling the constructor in your code. You also need to call the login
function. Also you don't want to put the await
in front of your constructor but in front of login
.
Code
const tools = new Tools();
await tools.login();
async
constructor functionsBe aware that you cannot use constructor calls (new Tools
) with await
. The reason is, that await
waits for the returned Promise to be resolved. But constructor functions cannot return a Promise as they need to return the newly created object.
That's why libraries like puppeteer use factory functions like puppeteer.launch
. These functions will create an object in addition to calling asynchronous functions afterwards. If you want to do something similar in your code, you can do it like this:
class Tools {
async initialize() {
// ...
}
static async create() {
const newObject = new Tools();
await newObject.initialize();
}
}
const tools = await Tools.create();
headless: true
Make puppeteer to run in Headless mode, meaning it will execute your code, but you'll not have any chrome openning
if you want to see what's hapenning in real time for debugging purposes, initialize puppeteer without the headleass mode
this.browser = ppt.launch({
headless: false,
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With