【问题标题】:Nodejs. Unhandled Promise Rejection节点。未处理的承诺拒绝
【发布时间】:2018-04-18 21:50:34
【问题描述】:

我正在尝试测试一些功能。在 routes.js 文件中,我放置了以下代码:

async function getPic(arg) {
    const browser = await puppeteer.launch(/*{headless: false}*/);
    const page = await browser.newPage();
    await page.goto(arg);
    await page.setViewport({width: 1000, height: 500})
    await page.screenshot({path: 'pic.png'});

    await broswer.close();
}

我读到了 async/await(这是我第一次使用它)。虽然我收到一条错误消息并且代码不起作用:

(node:5896) UnhandledPromiseRejectionWarning: Error: Navigation Timeout Exceeded
: 30000ms exceeded
    at Promise.then (C:\...\node_modules\puppeteer\lib\NavigatorWatcher.js:73:21
)
    at <anonymous>
(node:5896) 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:5896) [DEP0018] DeprecationWarning: Unhandled promise rejections are depre
cated. In the future, promise rejections that are not handled will terminate the
 Node.js process with a non-zero exit code.

不幸的是,我不知道这意味着什么。我在这里发现了关于 stackoverflow 的类似问题: NodeJS Unhandled Promise Rejection

但不幸的是,我并没有明确说明如何解决这个错误。

当我在独立节点环境中测试这段代码的 sn-p 时 - 意味着只有这段代码没有其他任何东西,就像我在我的项目中所做的那样,然后它以某种方式工作。

当我将此函数放在我的 routes.js 文件中,然后在发布事件发生时调用该函数时,我会收到错误消息。

下面是调用这个函数的代码:

app.post('/sc', function(req, res){
        var url = req.body.convo
        console.log(url)

        getPic(url);
    })

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您应该在调用异步函数之前使用 await 并将 await 调用包装到 try catch 构造中。

    app.post('/sc', async (req, res) => {
        const url = req.body.convo
        try {
          var picture = await getPic(url);
          //some logic or render response
        } catch (error){
           //here you should handle error
        }
    })
    

    【讨论】:

      【解决方案2】:

      您需要await getPic(url);

      另外你的浏览器在await broswer.close();中拼写错误

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-31
        • 2023-03-17
        相关资源
        最近更新 更多