0

I'm returning a JSON object via a $http.get. I'm able to get the result set, and it's an array, but when I try to access the object outside the fetch() I'm getting undefined. Not sure what I'm missing, in order to do this, any help is appreciated.

Thanks Jimi.

      myObject.fetch().then(function(myData) {
            $scope.myData = myData;
        });

       console.log($scope.myData) 
7
  • Is this how your code actually looks? In this case, the console.log will be running before the callback function has actually run and set $scope.myData Commented Aug 28, 2014 at 11:40
  • 1
    Put console.log(1) into the callback, and the similar with the number 2 outside. Run and see results. Thoughts? Commented Aug 28, 2014 at 11:41
  • so do I need to setTimeout? Commented Aug 28, 2014 at 11:42
  • What will it change? Commented Aug 28, 2014 at 11:43
  • @Jimi the point is that myObject.fetch() will be started and IMMEDIATELY continue with console.log($scope.myData), although the fetch hasn't finished yet. Whatever you want to execute after fetch() returns, put it into a function and call it from within fetch().then() Commented Aug 28, 2014 at 11:45

1 Answer 1

2

Your $scope.myData is undefined until fetch() finishes execution and calls the passed callback function.

in your example, console.log() is being called before the completion of myObject.fetch()

In the following example, it will most probably work (don't do it!)

setTimeout(function(){
 console.log($scope.myData) 
}, 2000);

I'm not telling you to do it this way, actually its a very bad way. best practice is to use that scope variable within the callback function only, since that where its actually set.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.