【问题标题】:How can I create async/await globally如何在全局范围内创建 async/await
【发布时间】:2018-10-29 17:19:00
【问题描述】:

我想使用一个全局变量,它有一个等待,像这样:

(async () => {
  const browser = await puppeteer.launch({headless: false})
  const page = await browser.newPage();
})()

然后在我的所有功能上使用它:

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();

}

运行它我得到这个错误:

ReferenceError: 页面未定义。

有什么方法可以让它工作吗?

【问题讨论】:

标签: javascript async-await puppeteer


【解决方案1】:

将承诺存储在全局变量中:

const pagePromise = (async () => {
  const browser = await puppeteer.launch({headless: false})
  return browser.newPage();
})();

然后你可以像以后一样使用它

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);

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);

【讨论】:

    【解决方案2】:

    这里的解决方案: 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();
    
    })()
    

    【讨论】:

      猜你喜欢
      • 2022-01-10
      • 2019-01-02
      • 2012-07-05
      • 2013-12-12
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-23
      • 2010-10-21
      相关资源
      最近更新 更多