使用unhandledRejection识别错误的承诺

时间:2018-05-03 20:13:50

标签: node.js asynchronous promise async-await puppeteer

我有这段代码:

// <-- add event on top of file
process.on("unhandledRejection", (reason, p) => {
        console.error("Unhandled Rejection at: Promise", p, "reason:", reason);
        // browser.close(); // <-- no need to close the browser here
});

const puppeteer = require('puppeteer');
async function getPic() {
    try{ // <-- wrap the whole block in try catch
      const browser = await puppeteer.launch(/*{headless: false}*/);
      const page = await browser.newPage();
      await page.setViewport({width: 1000, height: 500}); // <-- add await here so it sets viewport after it creates the page


      //await page.goto('https://www.google.com');  //Old way of doing. It doesn't work for some reason...

      page.goto('https://www.google.com/'); // async


      // wait for either of events to trigger
      await Promise.race([
        page.waitForNavigation({waitUntil: 'domcontentloaded'}),
        page.waitForNavigation({waitUntil: 'load'})
      ]);


      await page.screenshot({path: 'pic.png'});
      await browser.close(); // <-- close browser after everything is done
    } catch (error) {
      console.log(error);
    }
}

getPic();

我得到了这个错误:

Unhandled Rejection at: Promise Promise {
  <rejected> Error: Navigation Timeout Exceeded: 30000ms exceeded
    at Promise.then (C:\...\pupet test\node_modules\pupp
eteer\lib\NavigatorWatcher.js:71:21)
    at <anonymous> } reason: Error: Navigation Timeout Exceeded: 30000ms exceede
d
    at Promise.then (C:\...\pupet test\node_modules\pupp
eteer\lib\NavigatorWatcher.js:71:21)
    at <anonymous>

我读到只要Promise被拒绝就会发出'unhandledRejection'事件,并且在事件循环回合中没有错误处理程序附加到promise。

因此,从这个特定的错误消息中,我无​​法理解造成问题的原因。

那么我怎么能弄清楚哪个是错误的承诺,这样我才能进一步了解出了什么问题并减轻它?

0 个答案:

没有答案