I am trying to process uploaded file in S3. Since getObject is asyncronous main function ends before processing is done, and AWS kills lambda in 3-4 seconds.
Even worse, processing method also has async operations in it - it makes http calls.
On high level, my code looks like:
exports.handler = function(event, context) {
// Get the object from the event and show its content type
var bucket = event.Records[0].s3.bucket.name;
var key = event.Records[0].s3.object.key;
var params = {
Bucket: bucket,
Key: key
};
s3.getObject(params, function(err, data) {
if (err) {
...
} else {
processFile(data.Body.toString(), 0);
console.log("ok");
}
});
//need to wait here till processFile is done
};
processFile = function(content, start) {
... build url to call
http.get(url, function(res) {
console.log("Got response: " + res.statusCode + ");
processFile(content, start + 1);
});
}
I find out that there is async in nodejs but it is not included by amazon; Both require('async') or require('sleep) causes errors.
Lambda timeout configured to 60 seconds, but it exits in 3-4 seconds.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…