我正在编写一个发布到SNS主题的lambda函数,但它在任何结果返回之前超时,这是我的函数:
var AWS = require('aws-sdk'); // Used for calling SNS
var pg = require ('pg'); // Used to connect to Postgre
exports.handler = function (event, context) {
'use strict';
// Step 1 call database to get school hours
var conn = "postgres://OMITTED:OMITTED@sOMITTED.ap-southeast-2.rds.amazonaws.com/slm_appdb"; // Save this in env variable
var client = new pg.Client(conn);
client.connect();
// Step 1 call the database to get the hours
const query = client.query("select * from find_all_students_school_hours();", (err,res) => {
console.info('Query made',res.rows);
res.rows.forEach(function(row){
var command = {
username: row.username,
commands: {
working_days: row.working_days || 'Mon-Fri',
school_start_time: row.school_start_time || '08:00:00', // Save this in env variable
school_end_time: row.school_end_time || '17:00:00' // Save this in env variable
}
};
// Step 2 add command for agent by calling another lambda function through SNS
var sns = new AWS.SNS();
var params = {
Message: JSON.stringify(command),
Subject: 'Agent School Hours',
TopicArn: 'arn:aws:sns:ap-southeast-2:OMITTED:add-command-for-agent-topic'
}
console.log('params',params);
sns.publish(params, function(err,snsres){
if(err){
console.error('error',err);
} else {
console.info('published to sns',snsres);
}
});
});
context.done();
});
};
我已将此政策附加到lambda函数:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"sns:*"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
我在日志中得到的是params
数据,但之后没有任何内容,所以我从未到达console.error('error',err);
或console.info('published to sns',snsres);
,我给了它一分钟超时但仍然超时在它发布之前和日志中没有来自SNS的错误(见下图),有没有一种方法可以调试它以找出发生了什么?
答案 0 :(得分:0)
您正在呼叫context.done()
而不等待sns.publish
完成。
请记住,Javascript是异步的,所以当您在sns.publish
循环中执行I / O事件(res.rows.forEach()
)时,context.done()
将立即终止您的处理程序执行(并返回)等待你的SNS主题发表。