【发布时间】:2016-12-19 08:28:25
【问题描述】:
我正在编写一个 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')
}
【问题讨论】:
标签: node.js amazon-web-services asynchronous amazon-s3 aws-lambda