0

I'm new to js - I'm having trouble wrapping my head around how to return a value from an asynchronous operation using a callback. This is my current iteration of my code and it is still returning 'test undefined'. Can anyone check what I'm doing wrong? Thank you. Any help appreciated.

        var test = this.getImgurClientId(function (data) {
            console.log(data.Item.ClientId.S);  //this has a value
            return data.Item.ClientId.S;
        });
        console.log('test ' + test); //prints 'test undefined'



      this.getImgurClientId = function(callback) {
        AWS.config.update({
          accessKeyId: AWS_ACCESSKEYID,
          secretAccessKey: AWS_SECRET_ACCESSKEYID,
          region: AWS_DYNAMODB_REGION
        });

        var dynamodb = new AWS.DynamoDB();

        //console.log(dynamodb);

        var params = {
          AttributesToGet: [
            "ClientId"
          ],
          TableName: 'ServiceProvider',
          Key: {
            "ProviderName": {
              "S": "Imgur"
            }
          }
        };

        dynamodb.getItem(params, function(err, data) {
          if (err) {
            console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
            callback(err);
          } else {
//this query succeeds
            console.log("Query succeeded. " + JSON.stringify(data, null, 2));
            callback(data);

          }
        });

      }
user619804
  • 2,286
  • 12
  • 46
  • 71
  • 1
    Your assignment is breaking your asynchronicity. Lose the `var test=` part and just put the `this.getImgurClientId(function (data)` function call directly into the console.log statement. – LinuxDisciple Mar 21 '16 at 17:01
  • 3
    Famous dup? http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – elclanrs Mar 21 '16 at 17:02

1 Answers1

0

As you stated in your question, the call is asynchronous, so the only way to access your result is in the callback.

var test = this.getImgurClientId(function (data) {
            return data.Item.ClientId.S; //useless as the callback is asynchronous and is called in getImgurClient methdo
        });
        console.log('test ' + test); //the asynchronous call has not finished yet and you cannot wait for it

so:

var test = this.getImgurClientId(function (data) {
           data.Item.ClientId.S; //here is the only place where your datas are accessible
        });

For a more elegant way of handling asynchrous callbacks, you can take a look at the Promise API

n00dl3
  • 21,213
  • 7
  • 66
  • 76
  • Could I set the value of a $rootScope variable within the call back so that I can save the value for use outside the callback? I've been playing around with this approach but so far no luck. – user619804 Mar 21 '16 at 17:23
  • You should work with `$q`'s promises or scope events (`$scope.$broadcast("event");` and `$scope.$on("event",callback);`) that's the cleanest way to handle that... – n00dl3 Mar 21 '16 at 18:00
  • I'm sorry it's time for me to go home, I'll give you an example on promises tomorow if you want. – n00dl3 Mar 21 '16 at 18:02
  • Thanks, I did get it working with callbacks, it is not pretty though. – user619804 Mar 22 '16 at 03:25