Home » Javascript » amazon web services – Storing listObject data from AWS S3 SDK in Javascript

amazon web services – Storing listObject data from AWS S3 SDK in Javascript

Posted by: admin February 23, 2020 Leave a comment

Questions:

I am building a serverless application using AWS S3. In my web app, I have a table that lists the objects inside one of my S3 buckets. As my code is terribly spaghetti, I am trying to move the functions that build the table, get the S3 bucket object list, etc, into separate files and functions.
This is the code that gets the S3 list:

function listS3Objects() {
    s3.listObjects(function(err, data) {
        if (err) {
            return alert(err.message);
        }
    });
}

My question is: how can I access “data” from outside the callback function, so I can pass it as argument to other functions (like the one actually building the table)?

How to&Answers:

You should use Promises. For the AWS SDK calls you can add .promise() after it to make it into a promise, which allows for async/await syntax.