我正在编写一个 lambda 函数,需要加载存储在 S3 中的密钥。它不会经常改变,所以我不想每次调用 lambda 函数时都获取它,所以我想在容器旋转时加载它一次,然后在 lambda 容器的生命周期内保留该值。
但是,由于异步方法 getObject 这会导致问题,因为当主 module.export 代码运行时,文件可能尚未加载(特别是如果这是第一次运行一段时间并且正在创建容器)。
我已经使用 setTimeout 实现了一种解决方法,但我想看看推荐的方法是什么,以及我的方法是否存在任何问题,因为它感觉不对!
示例代码:
var AWS = require('aws-sdk')
var s3 = new AWS.S3();
var fileLoaded = false;
var params = {
Bucket: 'bucket-name',
Key: 'file-name'
};
s3.getObject(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else {
console.log('File loaded from S3');
fileLoaded = true;
}
});
exports.handler = (event, context, callback) => {
console.log('I am in the main procedure, but i might not have the file yet')
waitForFileLoadBeforeDoingSomething(event, context, callback)
};
function waitForFileLoadBeforeDoingSomething(event, context, callback){
if(!fileLoaded){
console.log('No file available to me yet, we will sleep')
setTimeout(function(){
waitForFileLoadBeforeDoingSomething(event, context, callback)
}, 300)
} else {
console.log('I have the file!')
doStuff(event, context, callback)
}
}
function doStuff(event, context, callback){
console.log('Now I can do the rest of the code')
//Do the actual code here
callback(null, 'success')
}