I'm trying to declare and initialize a const variable with global scope for the module and it needs to get value from the result of an async/await. Here is the code I've tried and the variable still holds undefined. How can I re-write this so I can still use a constant and this holds the desired value:
const puppet = require('puppeteer')
const browser = (async () => { await puppet.launch() })();
const page = (async () => { await browser.newPage() })();
console.log( "browser holds: " + util.inspect(page) );
// prints out undefined
I need to setup two separate pages that will be used throughout the app to load different pages and process them as needed.
For now, I'm able to do this by declaring the variables as 'var' and then assigning the value in a .then() . But I'd prefer to use a 'const' for these as a best practice.
Here is the code that lets me do this as a var and use it through out the app:
const puppet = require('puppeteer')
async function setupNewPuppetWithKeys(puppetBrowser, puppetPage ){
let browser = await puppet.launch();
let page = await browser.newPage();
page.setViewport({ width: 1280, height: 800 });
logger.infoLog("initialized values for - " + puppetBrowser + ", " + puppetPage )
return { [puppetBrowser] : browser , [puppetPage] : page };
}
var browserDev, pageDev;
setupNewPuppetWithKeys("browserDev", "pageDeV").then( (jsonResult) => {
logger.infoLog("In Then received : " + util.inspect(jsonResult) );
browserDev = jsonResult.browserDev;
pageDev = jsonResult.pageDev;
} );
// I declare more browser and page variables here .. but you get the idea with the one I've done above.