出现错误DeprecationWarning:不建议使用未处理的承诺拒绝。在节点js中

时间:2020-05-25 05:36:28

标签: node.js node-modules

我已经创建了test.js文件,并安装了一个npm库,当我运行该文件时,我遇到以下错误,我尝试使用npm i puppeteer这个库,但是当我尝试以下操作时却出现了错误安装它,所以我使用了这个库npm i puppeteer-core

(node:30075) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:30075) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这是我的test.js文件的完整代码

const puppeteer = require('puppeteer-core');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com');
  await page.screenshot({path: 'example.png'});
  await browser.close();
})();

任何人都可以帮助我为什么我遇到此错误吗?

1 个答案:

答案 0 :(得分:1)

使用async/await时,建议使用try/catch捕获错误并找出问题所在。

(async () => {
  try {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://example.com');
    await page.screenshot({path: 'example.png'});
    await browser.close();
  } catch (error) {
    console.log('error', error);
    // Do whatever you want, throw the error again if you want but it will just produce `UnhandledPromiseRejectionWarning` again, if you throw it again.
  }
})();