I have been trying (and failing) to load a file from an S3 bucket using s3.getObject in Node version 8.10.
I found a great post with a reply that almost worked here but the syntax doesn't quite work in 8.10 and no matter how I re-arrange the code I can't get it to work.
var AWS = require('aws-sdk')
var s3 = new AWS.S3();
var fileData = null;
exports.handler = (event, context, callback) => {
console.log('I am in the main procedure');
var params = {
Bucket: "change_for_your_bucket",
Key: "change_to_your_json_file"
};
fetchDataFromS3(params);
console.log('I am in the main procedure, the function above should be waiting but it is not');
waitForFileLoadBeforeDoingSomething(event, context, callback);
const s = JSON.stringify(fileData.Body.toString('utf-8'));
console.log(`this is the file: ${s}`);
console.log('I have the file!(dg.2)');
};
function fetchDataFromS3(params)
{
console.log('-------------- fetchDataFromS3:Start -------------------------');
// gets the object from s3 => promise
const uploadPromise = s3.getObject(params).promise();
// returns the body of the s3 object
uploadPromise
.then(function(data) {
console.log("successfully downloaded data");
fileData = data.Body.toString();
})
.catch(function download(err) {console.log(err,err.stack); throw err;});
console.log('-------------- fetchDataFromS3:Done -------------------------');
}
function waitForFileLoadBeforeDoingSomething(event, context, callback){
if(!fileData){
console.log('No file available to me as yet, lets sleep for a bit');
setTimeout(function(){
waitForFileLoadBeforeDoingSomething(event, context, callback);
}, 300);
}
}
the output is as follows.
Function Logs:
START RequestId: cb16f155-c0d7-11e8-ad01-f5991c5adaaf Version: $LATEST
2018-09-25T15:29:29.759Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf I am in the main procedure
2018-09-25T15:29:29.759Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf -------------- fetchDataFromS3:Start -------------------------
2018-09-25T15:29:29.811Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf -------------- fetchDataFromS3:Done -------------------------
2018-09-25T15:29:29.811Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf I am in the main procedure, the function above should be waiting but it is not
2018-09-25T15:29:29.811Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf No file available to me as yet, lets sleep for a bit
2018-09-25T15:29:29.812Z cb16f155-c0d7-11e8-ad01-f5991c5adaaf TypeError: Cannot read property 'Body' of null
at exports.handler (/var/task/dg3.js:17:39)
You can see that I'm not hitting the "successfully downloaded data" line and I can't work out if I've made a mistake and the function is still running asynchronously or if I have got the syntax of the promise wrong.