0

I'm attempting to assign a variable to one found in a controller from a promise taken from a factory, which pulls JSON data from a URL.

webApp = angular.module("App", []);

webApp.factory("getData", function($http) {
  var promise;
  var getData = {
    async: function() {
      if ( !promise ) {
        promise = $http.get(window.location+"/json").then(function (response) {
        return response.data;
        });
      }
      return promise;
    }
  };
  return getData;
});

webApp.controller("View", function(getData, $scope) {

  $scope.m = {}

  getData.async().then(function(m) {
    $scope.m = m;
    if ($scope.m == m) {
      console.log(true);
    }
  });

  console.log($scope.m);


});

Within the .then function, true is returned - but $scope.m is always returned as undefined.

Any help would be greatly appreciated!

phuzi
  • 12,078
  • 3
  • 26
  • 50
KeironO
  • 179
  • 1
  • 9
  • by _returned_ I assume `console.log($scope.m);` , it's simply outside of asynchronous callback `then()`, put it inside instead – Aleksey Solovey Nov 21 '17 at 14:12
  • Your function getData() is async, meaning the console.log($scope.m) will be run, before the $scope.m is assigned in the callback, learn more about async – high incompetance Nov 21 '17 at 14:13
  • I think the duplicate given in previous comment is wrong as this question doesn't say anything about asynchronous call. A question that links Promise with asynchronous would be more appropriate. – Adrien Brunelat Nov 21 '17 at 14:18
  • @AdrienBrunelat The [accepted answer](https://stackoverflow.com/a/14220323/754119) in the duplicate explain very well about promises. It does require a bit of reading but it's worthwhile for a new developer to learn :) I've seen this type of questions asked all the time by developers who don't understand the concept of asynchronous request and that answer provide all the relevant details – Alon Eitan Nov 21 '17 at 15:26
  • @AlonEitan ooh indeed it does, I didn't check the accepted answer. – Adrien Brunelat Nov 21 '17 at 15:50

1 Answers1

0

It's because promises are asynchronous methods. That means that your async call is executed in parallel with the console.log() line. Therefore, at that stage of the code, the variable is not assigned.

This would print the output:

webApp.controller("View", function(getData, $scope) {
  $scope.m = {}

  getData.async().then(function(m) {
    $scope.m = m;
    console.log(m);
    console.log($scope.m);
  });
});
Adrien Brunelat
  • 4,492
  • 4
  • 29
  • 42