GreenLake4964
GreenLake4964

Reputation: 776

AWS Lambda to list S3 buckets with listBuckets() has no effect

I am new to writing Lambda in JS. I want to be able to list the S3 buckets I have, however, below lambda doesn't return what I expect, ie. list of buckets. What have I done wrong? The only thing I am aware of is the line "console.log('hihi')" didn't print in my Cloudwatch log, so something going on when listBuckets() is invoked but I can't see any relevant logs... Tks in advance for any help !!

var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});

exports.handler = async (event) => {
    // Create S3 service object
    var s3 = new AWS.S3({apiVersion: '2006-03-01'});
    var params = {};
    // Call S3 to list the buckets
    s3.listBuckets(params, function(err, data) {
      console.log('hihi')
      if (err) {
        console.log("Error", err);
      } else {
        console.log("Success", data.Buckets);
      }
    });
    
    // TODO implement
    const response = {
        statusCode: 200,
        body: JSON.stringify('Hello from Lambda!'),
    };
    return response;
};

Upvotes: 1

Views: 1436

Answers (1)

Marcin
Marcin

Reputation: 238199

You are using async handler. Therefore, to your lambda does return before listBucket has a chance to execute. One way to overcome is through a Promise as shown in AWS docs.

Therefore, you could modify your code as follows:

var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});

exports.handler = async (event) => {
    
    const promise = new Promise(function(resolve, reject) {
        
      // Create S3 service object
      var s3 = new AWS.S3({apiVersion: '2006-03-01'});
      var params = {};
      // Call S3 to list the buckets
      s3.listBuckets(params, function(err, data) {
        console.log('hihi')
        if (err) {
          console.log("Error", err);
        } else {
          console.log("Success", data.Buckets);
        }
      });

    })
    return promise
};

Upvotes: 2

Related Questions