我在这里https://docs.atlas.mongodb.com/best-practices-connecting-to-aws-lambda/
使用了最佳实践MongoDB with Lambda示例我需要发布到SNS,但是由于callbackWaitsForEmptyEventLoop = false而无法发布,如果我取消注释,它可以正常工作,但是我的Lambda函数只是超时并且永远不会收到成功回调。
"use strict";
const MongoClient = require('mongodb').MongoClient;
const MONGODB_URI = process.env.MONGODB_URI; // or Atlas connection string
const AWS = require('aws-sdk');
const SNS_TOPICARN = process.env.SNS_TOPICARN;
const sns = new AWS.SNS({ apiVersion: '2010-03-31' });
let cachedDb = null;
function connectToDatabase(uri) {
console.log('=> connect to database');
if (cachedDb) {
console.log('=> using cached database instance');
return Promise.resolve(cachedDb);
}
return MongoClient.connect(uri)
.then(db => {
cachedDb = db;
return cachedDb;
});
}
function queryDatabase(db) {
console.log('=> query database');
return db.collection('items').find({}).toArray()
.then((data) => { return { statusCode: 200, data: data }; })
.catch(err => {
console.log('=> an error occurred: ', err);
return { statusCode: 500, data: null };
});
}
exports.handler = (event, context, callback) => {
context.callbackWaitsForEmptyEventLoop = false;
console.log('event: ', event);
connectToDatabase(MONGODB_URI)
.then(db => queryDatabase(db))
.then(result => {
console.log('=> returning result: ', result);
var params = {
Message: result.data,
Subject: 'Devices Lost Connection',
TopicArn: SNS_TOPICARN
};
sns.publish(params, function (err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
});
callback(null, result);
})
.catch(err => {
console.log('=> an error occurred: ', err);
callback(err);
});
};
答案 0 :(得分:0)
问题已解决,如果其他人遇到相同的问题,将其留在这里:
我需要在第二个函数的回调中执行处理程序回调:
sns.publish(params, function (err, data) {
if (err) console.log(err, err.stack);
else console.log(data);
callback(null, result);
});