Kevin
Kevin

Reputation: 45

Run Async method within puppeteer event

I am working with the puppeteer js library and I've reached a stumble. I need to run an async function within the page.on('request') event. Like so:

async function main(){
    page.on('request'){
        await sub()
    }
}

async function sub(){
    await page.goto(url)
}

When I run the above code: I get an error

await sub();
^^^^^

SyntaxError: await is only valid in async function

Please help

Upvotes: 1

Views: 1559

Answers (1)

Yaniv Efraim
Yaniv Efraim

Reputation: 6713

You are missing async in callback method (+ you have a syntax problem):

async function main(){
    page.on('request', async () => {
        await sub()
    });
}

async function sub(){
    await page.goto(url)
}

Upvotes: 2

Related Questions