Ad

How To Return A List Of SQS Queues In A Module Exports Function?

- 1 answer

I'm very new to node.js so I think I'm missing something obvious here.

I'm simply trying to get a list of SQS queues using aws-sdk and return them from a module to be accessible to other code. list_queues is the function in question.

The code below works to an extent, I see a "success" log and a log of a string array of all my queues, however, the function does not return that array to the caller and I don't understand why.

const AWS = require('aws-sdk');

AWS.config.update({region: 'eu-west-1'});
var sqs;
var sts = new AWS.STS();

sts.assumeRole({
  RoleArn: 'arn:aws:iam::xxxxx:role/UserRole',
  RoleSessionName: 'NodeDeveloperRoleSession'
}, function(err, data) {
  if (err) { // an error occurred
    console.log('Cannot assume role :(');
    console.log(err, err.stack);
  } else { // successful response
    console.log('Assumed role success :)');
    AWS.config.update({
      accessKeyId: data.Credentials.AccessKeyId,
      secretAccessKey: data.Credentials.SecretAccessKey,
      sessionToken: data.Credentials.SessionToken
    });
    sqs = new AWS.SQS({apiVersion: '2012-11-05'});
  }
});

exports.list_queues = function() {
  sqs.listQueues({}, function(err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("success");
      console.log(data.QueueUrls);
      return data.QueueUrls;
    }
  });
}

Any help is appreciated

Ad

Answer

exports.list_queues = function() { // 2. but you actually want to return from this one 
  sqs.listQueues({}, function(err, data) { <-----------------
    if (err) {                                              |
      console.log("Error", err);                            |
    } else {                                                |
      console.log("success");                               | 
      console.log(data.QueueUrls);                          |
      return data.QueueUrls; // 1. you are returning from this one 
    }
  });
}

there are two ways you can make it work

  1. Promise based
exports.list_queues = function() {
  return sqs.listQueues({}).promise().then((data) => data.QueueUrls);
}

// and in another file you would:

const {list_queues} = require('./list_queues.js');
list_queues.then((queues) => console.log(queues));
  1. Callback based
exports.list_queues = function(cb) { // notice I added callback here
  sqs.listQueues({}, function(err, data) {
    if (err) {
      console.log("Error", err);
    } else {
      console.log("success");
      console.log(data.QueueUrls);
      cb(data.QueueUrls);
    }
  });
}

// and in another file you would:

const {list_queues} = require('./list_queues.js');

list_queues(function(queues) {
  console.log(queues);
});

I strongly recommend you to use promise based approach, since it's much more readable and you can make use of async/await on it, which is great.

Ad
source: stackoverflow.com
Ad