我正在尝试创建一个lambda function on Netlify,为此我正在使用他们的Netlify Lambda CLI。
现在,在Promises上使用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
当在Promises上使用异步/等待时,为什么netlify-lambda记录UnhandledPromiseRejectionWarning? 我该如何解决?
答案 0 :(得分:2)
使用新的Node.js 8.10运行时,可以使用“ async”关键字声明新的处理程序类型,或者可以直接返回promise。
在AWS文档中,v8.10支持异步/等待,并且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)
};
}
};