【发布时间】: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? 我该如何解决这个问题?
【问题讨论】:
-
经过一些测试后,我能够让它工作,并在我的回答中展示了它,但我正在等待confirmation from Netlify if this is what they also expect。
-
Netlify 已确认对 netlify 函数的异步函数调用也不应该有回调。
标签: node.js async-await aws-lambda es6-promise netlify