Prometheus
Prometheus

Reputation: 33655

Undefined in the following when returning object

I have a function with this in:

1:  var object = get_resource($scope, CbgenRestangular, $stateParams.scheme_id);
2:  console.log(object)

Which runs this:

get_resource = function ($scope, CbgenRestangular, id){
    CbgenRestangular.one('scheme', id).get().then(function(object){
             console.log(object)
        return object
    })
},

My issue is that within get_resource function console.log returns the object perfect, however line 2 in the above code it's undefined, why?

This should be the same object thats in the get_resource function, why is it undefined when I return it.

Upvotes: 0

Views: 54

Answers (2)

Christian
Christian

Reputation: 7429

Javascript is asychronous. This is important to understand. It means if you call a function which does an ajax call (a long running process), you need a callback.

Your code can't work because you have a function where you call another function. the second function then returns an object. but function 1 doesn't know that, so it return (undefined) immediately.

This should work.

get_resource = function ($scope, CbgenRestangular, id, _callback){
   CbgenRestangular.one('scheme', id).get().then(function(object){
      _callback(object);
 })
},

get_resource($scope, CbgenRestangular, $stateParams.scheme_id,function(_obj){
  console.log(obj)
});

By the way, you should never name a variable "object". This word is reserved..

Upvotes: 1

basilikum
basilikum

Reputation: 10536

The function get_resource doesn't have a return statement, so it's no surprise that you get undefined as a result. You do have a return statement inside the function that you pass to the then function, but this doesn't return from the "outer" function.

What you are dealing with here, are promises. The get function apparently returns a promise:

var promise = CbgenRestangular.one('scheme', id).get();

To get the result of that promise, you can use the then function, as you did inside the get_resource function.

Now, if you want to handle that promise outside of this function, you can simple return the promise and then do the same thing:

get_resource = function ($scope, CbgenRestangular, id){
    return CbgenRestangular.one('scheme', id).get().then(function(object){
             console.log(object)
        return object
    })
}, 

//.....

var promise = get_resource($scope, CbgenRestangular, $stateParams.scheme_id);
promise.then(function (object) {
    console.log(object);
});

Upvotes: 2

Related Questions