Evaluating promise in REPL loop with VSCode and Pupeteer

Viewed 418

enter image description here

I'm getting started with puppeteer but have minimal node experience. I'm interested in debugging and trying out pieces of code in a REPL loop. So far I have the following:

const puppeteer = require('puppeteer');


(async () => {

const browser = await puppeteer.launch({
headless: false,

});
const page = await browser.newPage();
await page.goto('https:yahoo.com');
 await page.screenshot({path: 'example.png'});

 await browser.close();
})();

I tried to take a second screen shot by entering :

 page.screenshot({path: 'example1.png'});

but this returns a promise. Is there a way to evaluate the result within the REPL loop

EDIT:

I entered both lines into the REPL at the bottom of the debug console, the output is in the screenshot. Am I doing something wrong?

enter image description here

EDIT2:

I entered your code into the debug window REPL at the bottom of the debug console, the output is in the screenshot.

enter image description here

1 Answers

If you want to pay with the result in the REPL you'd have to do something like this:

var res; page.screenshot({path: 'example1.png'}).then(r => {res=r;console.log('done')});

The done string is printed you'll have the result in your res variable so you can play with it.

Step by Step:

  • var res is declaring an empty variable so you can use it later

  • page.screenshot({path: 'example1.png'}) will return a promise, hence the .then right after it

  • .then receives a function that will be called asynchronously when the promise is resolved. That function will be called with some input.

  • r => {res=r;console.log('done')} this is the anonymous function passed to the then of that promise. The argument passed by page.screenshot(...).then will be stored in the r param/variable.

  • res=r; this sets to the res variable the argument sent from the resolution of the promise.

  • console.log('done') is just there so you will know when the promise is resolved.

  • after that, you can inspect the res variable to understand in detail whatever is there.

You can use this approach for ANY type of promise resolution debug, since when in the console (at the moment) we don't have the ability to run something like var res = await page.screenshot({path: 'example1.png'})

Related