0

I'm trying to have the two lines in my initialize method be run once so I can call other methods after this.browser and this.page are set. I can't do this in the constructor as they're async.

When I run this code I get UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'goto' of undefined.

How can I set these variables so they can be used in other methods?

const puppeteer = require('puppeteer');

class Bot {
    constructor() {}

    async initialize() {
        this.browser = await puppeteer.launch({ headless: false });
        this.page = await this.browser.newPage();
    }

    async login() {
        await this.page.goto('https://reddit.com/login/', { waitUntil: 'domcontentloaded' });
    }

    ...

}

const bot = new Bot();
bot.initialize();
bot.login();
nandesuka
  • 699
  • 8
  • 22
  • 1
    You need to wait the initialize execution `const bot = new Bot(); bot.initialize().then(()=>bot.login());` – Troopers Jul 27 '22 at 07:32
  • Or `await` the promises. You can't syncify async code. – ggorlen Jul 27 '22 at 14:55
  • Does this answer your question? [Call An Asynchronous Javascript Function Synchronously](https://stackoverflow.com/questions/9121902/call-an-asynchronous-javascript-function-synchronously) – ggorlen Jul 27 '22 at 14:56

0 Answers0