I've got the following problem: I have a page evaluation in puppeteer which includes asnychronous parts. I want to return the value from the asynchronous part to puppeteer, however, it just returns undefined without waiting for the Promise to resolve. Does anybody how to solve the problem?
My Sample code:
const puppeteer = require('puppeteer');
async function testing(num) {
const browser = await puppeteer.launch({
headless: false,
ignoreHTTPSErrors: true
});
const page = await browser.newPage();
const evaluating = await page.evaluate((num) => {
//some synchrnous stuff (declaring some variablesand so on...)
function lookForNumber(num) {
if (num > 2) {
var asyncstuff = setTimeout(function () {
if (num > 10) {
console.log('number is greater than 9');
var whatIwantToRetrun = 'ten';
return Promise.resolve(whatIwantToRetrun);
//return here
}
if (num > 5 && num < 10) {
console.log('number is samller than 10');
var whatIwantToRetrun = 'nine';
return Promise.resolve(whatIwantToRetrun);
//return here
}
else {
num++;
lookForNumber(num)
}
}, 2000);
}
}
lookForNumber(num)
}, num)
console.log(evaluating); // returns undefined before function has finished
}
testing(4)
Puppeteers example:
const result = await page.evaluate(() => {
return Promise.resolve(8 * 7);
});
console.log(result); // prints "56"
According to this link and the updated API, puppeteer always evaluates the code, and, if the evaluation is a promise, waits for the promise to resolve and returns the promise value.
Thanks in advance for any help!
Edit: I figured it out!