I can't figure out what these round brackets enclosing an async function are for. What are they denoting?
const puppeteer = require('puppeteer');
(async() => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
// more codes here
})();
What you're seeing is called an Immediately Invoked Function Expression. They want to run this code right away, and so there's a pair of ()
at the end in order to immediately call the function. But just adding those would result in illegal syntax, so in addition the function as a whole needs to be wrapped in parentheses.
If you're curious why they are creating a function just to immediately call it, they're doing it in order to be able to use the await
keyword. await
can only be used in an async
function, and therefore can't be at the root level of a file. There are other reasons which can motivate the use of an IIFE, but that's the reason in this case.