-1

I'm trying to create a lambda function to create new IAM user in AWS using Nodejs SDK, the function iam.createUser() works great but I couldn't retrieve the callback data before my function finishes. I'm not familiar with Nodejs so here I am asking for experts' help.

Here's the piece of code where I call createUser():

var retMessage = '';
var params = {
  UserName: "foo.bar";
};
iam.createUser(params, function(err, data) {
  if (err) {
    retMessage = err;
  } else {
    retMessage = data;
  }
}); 
console.log(retMessage);

When my function finishes, all i got from retMessage is null.

So how do I get those callback values?

Casper
  • 1,663
  • 7
  • 35
  • 62
  • 1
    Your console.log is happening before the function finishes. Keep in mind that javascript is asynchronous, meaning it fires off createUser, then calls console.log, **it will not wait for createUser** before moving on – Derek Pollard Sep 28 '16 at 01:10
  • @Derek well that's why I asked the question – Casper Sep 28 '16 at 16:27
  • 1
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Mark B Sep 28 '16 at 18:26

1 Answers1

0

Why don't you just move the console.log (or data handling) call inside the callback? Like

var params = {
  UserName: "foo.bar";
};
iam.createUser(params, function(err, data) {
  if (err) {
    retMessage = err;
  } else {
    retMessage = data;
  }
  console.log(retMessage);
  // ...do your data handling...
}); 
Diego Ferri
  • 2,657
  • 2
  • 27
  • 35
  • My point is I need the value of `retMessage` outside of this function – Casper Sep 28 '16 at 16:30
  • I think there's now way to do that with a callback. If you need a more "synchronous" style you should try something else, promises for instance. – Diego Ferri Sep 29 '16 at 07:48