[英]How can I create async/await globally
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.
ReferenceError:页面未定义。
There is some way to make it work? 有什么办法可以使它起作用?
Store the promise in the global variable: 将promise存储在全局变量中:
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 解决方案在这里: 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();
})()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.