Puppeteer example without async/await


Given puppeteer is installed:

npm install puppeteer

The current example uses async/await:

const puppeteer = require('puppeteer');

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

But how do you write the equivalent without async/await?

It’s pretty straightforward once you realize all the methods return promises:

const puppeteer = require('puppeteer');

let _browser;
let _page;

puppeteer
  .launch()
  .then((browser) => (_browser = browser))
  .then((browser) => (_page = browser.newPage()))
  .then((page) => page.goto('https://example.com'))
  .then(() => _page)
  .then((page) => page.screenshot({ path: 'example.png' }))
  .then(() => _browser.close());

However, writing it this way is a bit more verbose because you need to make sure the right object is passed in the thenable chain.



Please support this site and join our Discord!