2

I'm sure I'm missing something obvious and basic about synchronicity, but I cannot get my head around how this is supposed to work...

$scope.foo=[];

getFoo(url) {
  $scope.foo=$http.get(url).then(function (response) {
    var foo = [];
    //process response to get foo array. Console.log returns as expected here.
    return foo;
  });
}

This just seems to set $scope.foo to the promise object. What am I missing? How do I actually use the result of the promise in the rest of my code?

Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
nwhaught
  • 1,562
  • 1
  • 15
  • 36
  • You access it in your then callback, so assign it to your scope there. Unless you can use the await keyword. Promises are async, so you don't return out and expect to use that returned value in a synchronous manner. That simply returns a value to the next chained .then. – ste2425 May 24 '17 at 20:01
  • 1
    As you wrote, you already know where to process and log the response. What's the problem? – Bergi May 24 '17 at 20:01
  • `$scope.foo` is another promise, so wait for it: `$scope.foo.then(…)` – Bergi May 24 '17 at 20:02
  • response is the returned data from get(url). I also don't see the problem. `return response;` is probably what you want... – nugenjs May 24 '17 at 20:02
  • You're right, `$scope.foo=$http.get(url).then(...)` is setting `$scope.foo` to the promise object, you shouldn't need to return from your callback, asynchous code won't return the callback's return value in that sense, that's why a callback exists: to do something with the value there. Try setting `$scope.foo = response.data;` instead and see how that works – Patrick Barr May 24 '17 at 20:02
  • This sure seems a lot like [How do I return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call/14220323#14220323). – jfriend00 May 24 '17 at 20:17
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Estus Flask May 24 '17 at 20:59

1 Answers1

4

Rather than returning foo, you'll want to move the assignment inside of the callback:

getFoo(url) {
  $http.get(url).then(function (response) {
    var foo = [];
    // process response to get foo array...
    $scope.foo = foo;
  });
}

With promises, the value returned by a .then() callback will only be available to yet another .then() callback when they're chained together:

$http.get(url).then(function (response) {
  var foo = [];
  // process response to get foo array...
  return foo;
}).then(function (foo) {
  $scope.foo = foo;
});
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199