0

I have this helper function:

const listFileKeysInSpaceByPrefix = async (prefix) => {
    var params = {
        Bucket: process.env.S3_BUCKET_NAME,
        Prefix: prefix,
    };
    let fileKeys;
    await s3.listObjects(params, function (err, data) {
        if (err) {
            console.log(err, err.stack);
            next(err);
        }
        let keys = [];
        data["Contents"].forEach(function (obj) {
            keys.push(obj.Key);
        });
        console.log("key1", keys);
        fileKeys = keys;
    });
    return fileKeys;
};

And I called the helper function within a route like this:

const keyToBeDeleted = await listFileKeysInSpaceByPrefix(uploadSpaceFolder);
console.log("keys",keyToBeDeleted);

The Result on my console however looks thus:

keys undefined
key1 ['adamter/rr0.png', 'adamter/rt0.png']

I need to get the array in my response when I call the function but I seem not to find a way around this.

mykoman
  • 1,715
  • 1
  • 19
  • 33
  • `s3.listObjects()` does not return a promise. Usually functions that take a callback don't. It's *either* a callback *or* a promise in most cases. – VLAZ Sep 21 '21 at 12:25
  • @VLAZ So how do you recommend that I fetch the returned values in the keyToBeDeleted variable? My problem still remains unsolved – mykoman Sep 22 '21 at 05:48
  • [How to return the response from an asynchronous call](https://stackoverflow.com/q/14220321) | [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/q/23667086) | [How do I convert an existing callback API to promises?](https://stackoverflow.com/q/22519784) – VLAZ Sep 22 '21 at 08:01

1 Answers1

0

Try with callback function.

const listFileKeysInSpaceByPrefix = (prefix, callBackFn) => {
  var params = {
    Bucket: process.env.S3_BUCKET_NAME,
    Prefix: prefix,
  };
  s3.listObjects(params, function (err, data) {
    if (err) {
        console.log(err, err.stack);
        next(err);
    }
    let keys = [];
    data["Contents"].forEach(function (obj) {
        keys.push(obj.Key);
    });
    console.log("key1", keys);
    callBackFn(keys);
  });
};

function yourFunction() { 
  function callBackFn(keyToBeDeleted) { 
    // access keyToBeDeleted 
    // add your logic here 
  }

  listFileKeysInSpaceByPrefix(uploadSpaceFolder, callBackFn); 
}
Ganesan C
  • 269
  • 1
  • 3
  • 9
  • This doesn't exactly solve my problem. How can I access the values in the variable keyToBeDeleted. I don't want to log the response rather I want to access the results when I call that function – mykoman Sep 22 '21 at 05:51
  • function yourFunction() { function callBackFn(keyToBeDeleted) { // access keyToBeDeleted // add your logic here } listFileKeysInSpaceByPrefix(uploadSpaceFolder, callBackFn); } – Ganesan C Sep 22 '21 at 06:07
  • Can you please edit your answer for clarity – mykoman Sep 22 '21 at 06:20
  • Modified the code. Now check it pls. – Ganesan C Sep 22 '21 at 07:53