1
function graphreport(agentList) {

    var b;
    var self = this;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        b = data.data.users.length;
    });

    console.log(b);
}

First console.log will return the value. Second console log will return undefined. How do get the variable outside a method? BTW, I'm resolving a promise in the method.

lin
  • 17,956
  • 4
  • 59
  • 83

2 Answers2

4

You could achieve this by using promises or a callback. But you will not be able to make it like you tried to in just one linear procedure. Get aware of async JavaScript bevhaviors. Here is an example fiddle.

With promises

function graphreport(agentList) {

    var b;
    var self = this;
    var deferred = $q.defer();
    var promise = deferred.promise;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        b = data.data.users.length;
        deferred.resolve(data.data.users.length);
    });

    promise.then(function (b) {
        console.log(b);
    });
}

With callback function

function graphreport(agentList) {

    var self = this;

    agentList.getAgentsList().then(function (data) {
        self.agents = data.data.users;
        console.log(data.data.users.length);
        myCallack(data.data.users.length);
    });

    function myCallack(b) {
      console.log(b);
    }
}

With co & yield like in this demo fiddle.

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function ($timeout, $q) {

   co(function *() {
     var deferred = $q.defer();
     var promise = deferred.promise;

     function someAsync() {
        $timeout(function () {
              deferred.resolve('test');
        }, 250);
     }

     someAsync();
     var b = yield promise;
     console.log(b);
   });
});
lin
  • 17,956
  • 4
  • 59
  • 83
1

Since, your var b only gets resolved after promise resolution, you have to retrieve it asynchronously. One of the ways is you can use callback as shown below. So when promise is resolved b gets returned with your callback function.

function graphreport(agentList, callback) {
    var b;
    var self = this;
    agentList.getAgentsList()
            .then(function (data) {
                self.agents = data.data.users;
                console.log(data.data.users.length);
                b = data.data.users.length;
                //return the callback method
                return callback(null, b);
            });
}

graphreport(list, function(err, b){
  if(!err){
   console.log(b);
   }
});
mp77
  • 428
  • 3
  • 7