【问题标题】:Why netlify-lambda logs an UnhandledPromiseRejectionWarning when using async/await on Promises?为什么 netlify-lambda 在 Promise 上使用 async/await 时会记录 UnhandledPromiseRejectionWarning?
【发布时间】:2019-05-04 02:51:04
【问题描述】:

我正在尝试创建一个lambda function on Netlify,我正在使用他们的Netlify Lambda CLI

现在,我在 Promise 上使用 async/await 时遇到了一个问题,因为即使我使用的是 try/catch,它也会记录 UnhandledPromiseRejectionWarning。

这是一个演示:

import fetch from "node-fetch";

exports.handler = async function(event, context, callback) {
    try {
        const response = await fetch("https://api.chucknorris.io/jokes/random");
        const data = await response.json();

        callback(null, {
            statusCode: 200,
            body: data.value
        });
    } catch (err) {
        console.error(err);
    }
};

日志:

netlify-lambda: Starting server
Lambda server is listening on 9000
Hash: 533f41e1d4248894ae20
Version: webpack 4.26.1
Time: 966ms
Built at: 11/28/2018 10:59:44 PM
  Asset      Size  Chunks             Chunk Names
test.js  18.3 KiB       0  [emitted]  test
Entrypoint test = test.js
[0] external "stream" 42 bytes {0} [built]
[1] external "zlib" 42 bytes {0} [built]
[2] external "url" 42 bytes {0} [built]
[3] external "http" 42 bytes {0} [built]
[4] external "https" 42 bytes {0} [built]
[5] ./test.js + 1 modules 40.8 KiB {0} [built]
    | ./test.js 1.14 KiB [built]
    | ../node_modules/node-fetch/lib/index.mjs 39.6 KiB [built]
Request from ::1: GET /test
Response with status 200 in 685 ms.
(node:99167) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'statusCode' of undefined
    at callback (/Users/nunoarruda/Desktop/test/node_modules/netlify-lambda/lib/serve.js:22:42)
    at /Users/nunoarruda/Desktop/test/node_modules/netlify-lambda/lib/serve.js:41:21
    at process.internalTickCallback (internal/process/next_tick.js:77:7)
(node:99167) 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:99167) [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.

相关 GitHub 问题:https://github.com/netlify/netlify-lambda/issues/43

为什么 netlify-lambda 在 Promise 上使用 async/await 时会记录 UnhandledPromiseRejectionWarning? 我该如何解决这个问题?

【问题讨论】:

标签: node.js async-await aws-lambda es6-promise netlify


【解决方案1】:

使用新的 Node.js 8.10 运行时,可以使用“async”关键字声明新的处理程序类型,也可以直接返回一个 Promise。

在 AWS 文档中,v8.10 支持 async/await,并且 Netlify 的新默认设置现在使用此版本。 In the AWS docs,示例显示这两种新的处理程序类型删除了回调的使用。我们应该在使用 Netlify 的函数中做同样的事情。

我能够使用以下代码在本地删除错误消息,而无需使用回调:

import fetch from "node-fetch";

exports.handler = async function(event, context) {
    try {
        const response = await fetch("https://api.chucknorris.io/jokes/random");
        if (!response.ok) { // NOT res.status >= 200 && res.status < 300
            return { statusCode: response.status, body: response.statusText };
        }
        const data = await response.json();

        return {
            statusCode: 200,
            body: data.value
            // if you want to return whole json string
            // headers: { 'Content-Type': 'application/json' },
            // body: JSON.stringify(data)
        };
    } catch (err) {
        console.log(err); // output to netlify function log
        return {
            statusCode: 500,
            body: err.message // Could be a custom message or object i.e. JSON.stringify(err)
        };
    }
};

【讨论】:

  • 您能否详细说明您删除asyncawait 的原因? “因为 node-fetch 使用了 Promise。” 没有意义
  • @8eecf0d2 一开始我真的搞砸了我的假设。我还在使用非常旧版本的 CLI 进行测试。从此编辑重新开始。
  • 我想说的是(很糟糕?),没有 async/await 你可以让处理程序直接返回一个承诺。但是,这个答案应该得到async/await 的解决方案,因为这就是他的要求。回调应该被移除。
  • 我更新了 issue here 以显示返回承诺而不是 async 函数处理程序的工作示例。
猜你喜欢
  • 2020-03-22
  • 1970-01-01
  • 1970-01-01
  • 2018-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多