1

I am trying to read the buckets in an account and save the list to a variable that can be accessed by other functions.

I am trying using a global variable.

Result: Global variable value not retained/saved.

Node: v10 Code:

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

s3 = new AWS.S3({apiVersion: '2006-03-01'});
let blist;
getBuckets();
console.log("list: " + blist);

async function getBuckets() {
     let response = await s3.listBuckets().promise();
      // do your processing
      var buckets = response.Buckets.map(x=>x.Name);
      console.log("buckets: " + buckets);
      blist = buckets;
      //return bnames;
}

Output:

Output:

(GV) List: undefined  (blist) 
(LV) Buckets: [all good]

Global variable value is undefined.

Can someone please help me? All I need is to access the list of bucket names from a different function.

1
  • s3.listBuckets() does't return text, it returns a request object... which you don't need when invoking it asynchronously, as you are doing. docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/… Your return ndata; in the callback doesn't make sense, because the turn value from callbacks is discarded. Commented Jun 10, 2018 at 16:18

2 Answers 2

2

s3.listBuckets is an asynchronous function so when you assign to a variable you won't get expected result. you better consider using promises to chain them or use async/await.

Using promises:

s3.listBuckets().promise()
       .then((response) => {
          // do your processing
        });

Using async/await:

async function someFn() {
     let response = await s3.listBuckets().promise();
      // do your processing
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, @dilip for the explanation. I tried using the async function and it is still the same. I have now modified the initial post with the updated program. blist global variable is still undefined, but buckets local variable gets all the bucket names.
0

This minimal code works:

import S3 from "aws-sdk/clients/s3.js";

const main = async () => {
  const s3 = new S3({ apiVersion: "2006-03-01" });

  const buckets = await s3.listBuckets().promise();
  console.log(JSON.stringify(buckets));
};

(async () => {
  try {
    await main();
  } catch (e) {
    console.error(e);
  }
})();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.