Trying to access a S3 bucket from a node.js express application. I'm trying to return the JSON file from the bucket in the form of a JSON object. Here's the code:

    let gets3 = function(file) {
        devs3();
        return new Promise(function(resolve, reject)  {
            var params = {
                Bucket: S3_BUCKET,
                Key: file
            }
            var s3 = new aws.S3();
            try {
            s3.getObject(params, function(err, data) {
                var myfile = JSON.parse(data.Body.toString());
                resolve(myfile);
            });
            } catch (err) {
                reject(err);
            }
        });
    }


module.exports = {


    fetchEvents : function(cata) {
        var myJson;
        switch (cata) {

            case "Pr":
                myJson = 'primaryEvents.json';

            case "Sc":
                myJson = 'secondaryEvents.json';

            case "Po":
                myJson = 'postEvents.json';
        }

        let gets3init = gets3(myJson);

        gets3init.then(function(file) {
            console.log('From Fetch Events: ' + JSON.stringify(file));
            return file;
        });

    }
}

devs3() just sets the S3 login information and runs aws.config.setPromisesDependancy. In my main app.js, I run fetchEvents("Pr") and then try and display it. In my console, it successfully displays the contents of the json file, however the application exists with a type error: cannot read property 'n' of undefined, where n is the name of the first element in the Json file. One thing to note is that this error displays in the console before the JSON file is printed, thereby showing that the function is not waiting for gets3 to finish and return the file. Is there anyway to force the application to wait (this happens on a page load) for promise to resolve?

1 Answers

0
tomtomy8 On Best Solutions

Thanks to @Bergi for pointing me in the right direction and helping me get this answer. Essentially, I was using promises wrong from the start. I needed to return the promise from the fetchEvents function, not the data, and then use this in the calling code in order to only proceed once the promise has been resolve.
fetchEvents

module.exports = {


    fetchEvents : function(cata) {
        var myJson;
        switch (cata) {

            case "Pr":
                myJson = 'primaryEvents.json';
                break;

            case "Sc":
                myJson = 'secondaryEvents.json';
                break;

            case "Po":
                myJson = 'postEvents.json';
                break;
        }

        return gets3(myJson);

    }
}

Calling Code

app.get('/PrEvents', function(req, res) {
    var myCata = req.path.replace('Events', '').replace('/', '');
    fetch(myCata).then(function(events) {
      res.render('pages/eventsShowTemp', {
        console.log(events);
      });
    });
  });