Ad

Puppeteer Define Browser And Page Synchronously

At the start of the Puppeteer tutorial, it says to do this:

const puppeteer = require('puppeteer');
(async () => 
{
    await page.goto('https://example.com');
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await browser.close();
})();

This seems odd to me as the whole thing is wrapped inside an asynchronous function. What if I want to wait until this finishes to continue?

Edit - Why this seems odd to me:
What if all my code relied on the browser, i.e., there is nothing I can do outside this async function. Then my code would look like this:

//nothing up here
(async () => 
{
    //EVERYTHING is in here
})();
//nothing down here

This seems weird because I might as well do everything synchronously instead of wrapping my entire program in an async function.

Ad

Answer

Reason for the async function

You need to wrap the code containing await instructions inside an async function for backwards compatibility reasons. Before ES7, you could use the word await as variable or function name, meaning this was valid code:

var await = 123;
console.log(await);

To not mess with existing code, the await keyword only works inside of async functions, meaning to write code like await page.goto(..) you have to put it inside an async function like the one you are using.

Waiting for the code to finish

To wait until the code has finished, you can just continue after the last await statement like this:

(async () => {
    // ...
    await browser.close();

    // continue with more code
})();
Ad
source: stackoverflow.com
Ad