I want to use a variable globally that has an await, something like this:
(async () => {
const browser = await puppeteer.launch({headless: false})
const page = await browser.newPage();
})()
And later use it on all my functions:
async function login() {
await page.goto(urls.login);
await page.type('#username', user);
await page.type('#password', pw);
page.click('[type="submit"]');
await page.waitForNavigation();
}
Running it I get this error:
ReferenceError: page is not defined.
There is some way to make it work?
Store the promise in the global variable:
const pagePromise = (async () => {
const browser = await puppeteer.launch({headless: false})
return browser.newPage();
})();
Then you can later use it like
async function login(page) {
await page.goto(urls.login);
await page.type('#username', user);
await page.type('#password', pw);
page.click('[type="submit"]');
await page.waitForNavigation();
}
pagePromise.then(login).catch(console.error);
or
async function login() {
const page = await pagePromise;
await page.goto(urls.login);
await page.type('#username', user);
await page.type('#password', pw);
page.click('[type="submit"]');
await page.waitForNavigation();
}
login().catch(console.error);
Solutions here: https://github.com/tc39/ecmascript-asyncawait/issues/9
(async () => {
const browser = await puppeteer.launch({headless: false})
const page = await browser.newPage()
async function login() {
await page.goto(urls.login, {waitUntil: 'networkidle2'});
await page.type('#user', user);
await page.type('#password', pw);
await page.click('[type="submit"]');
await page.waitForNavigation();
await page.screenshot({path: 'after-login.png'});
}
login();
})()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.