为什么AWS Lambda函数总是超时?

我正在testingaws lambda,使用4.3版本的nodejs。 我能够在控制台testing中成功完成处理函数中的所有语句,包括连接到我们vpc中的mongodb主机。 但是,function总是超时。 我发现了几个post和资源,讨论使用callback,设置上下文的属性和IAMangular色权限,但无论我做什么,它总是结束超时。 当前代码:

'use strict'; var Mongoose = require('mongoose'); var Device = require('./device_model'); var Alarm = require('./alarm_model'); var Event = require('./event_model'); var mongoConnection = process.env.MONGO_URL; var connection = Mongoose.connect(mongoConnection); Mongoose.connection.once('open', function() { console.log("Connecting to mongo at: " + mongoConnection); console.log("Mongoose connection in lambda opened"); }); Mongoose.connection.on('error', function(){ console.error("Error creating mongoose connection in lambda, exiting!"); process.exit(1); }); exports.check_alarms = function(event, context, callback) { context.callbackWaitsForEmtpyEventLoop = false; console.log("The incoming event: " + JSON.stringify(event)); var device = null; Device.findByUUID(event.uuid, function(error, result){ if(!error){ device = result; console.log("the device: " + JSON.stringify(device)); if(event.Ale && event.Ale.length > 0) { console.log("We have an alarm, checking if already set"); callback(null, {"status":"alarms"}); } else { console.log("Event contains no alarm; checking for historic active"); callback(null, {"status":"no alarms"}); } } else { console.log("there's a problem on mongo"); callback("problem", "status not so good"); } }); callback(null, {"status":"outside of device find block"}); } 

你有一个错字:

 context.callbackWaitsForEmtpyEventLoop = false; 

应该:

 context.callbackWaitsForEmptyEventLoop = false; 

以下是关于callbackWaitsForEmptyEventLoop行为的文档说明:

callbackWaitsForEmptyEventLoop

默认值是true 。 此属性仅用于修改callback的默认行为。 默认情况下,callback将等待,直到Node.js运行时事件循环为空,然后冻结进程并将结果返回给调用者。 您可以将此属性设置为false以请求AWS Lambda在调用callback后立即冻结该进程,即使事件循环中有事件。 AWS Lambda将冻结进程,Node.js事件循环中的任何状态数据和事件(下一次调用Lambda函数时处理事件循环中的任何剩余事件,以及AWS Lambdaselect使用冻结进程)。 有关callback的更多信息,请参阅使用callback参数 。

最小的例子:

 // Times out due to typo exports.function1 = (event, context, callback) => { setInterval(() => console.log('Long wait'), 100000); context.callbackWaitsForEmtpyEventLoop = false; callback(null, 'Hello from Lambda'); }; // Returns successfully exports.function2 = (event, context, callback) => { setInterval(() => console.log('Long wait'), 100000); context.callbackWaitsForEmptyEventLoop = false; callback(null, 'Hello from Lambda'); };