3

I'm using $q in a method to get an array of objects. I also have a method called getItems which makes use of this promise (all).

I use all a second time at the bottom, to do stuff with $scope.list. The code has to be wrapped inside all().then(function() { ... } so it only triggers when $scope.list ready.

var all = function() { return $q.all([service.getAllItems()]) }

var getItems = function() {
  all().then(function(value) {
     $scope.list = JSON.parse(value)
  }, function(reason) {
    $scope.result = reason
  })
}

getItems()

all().then(function() {
  // do stuff with $scope.list
}

This works...almost. Sometimes the first all finishes first and sometimes the second one. So sometimes $scope.list has the objects and sometimes it's empty.

How to create a new promise that only triggers when all fetches the array of objects?

alex
  • 7,111
  • 15
  • 50
  • 77
  • One can **return** the promise to **chain** from it. Remember the rule of thumb for functional programming is **always return something**. – georgeawg Jan 26 '16 at 07:49
  • Look at this question for more [Angular execution order with `$q`](http://stackoverflow.com/questions/34324153/angular-execution-order-with-q/34326388#34326388). – georgeawg Jan 26 '16 at 07:52
  • @georgeawg So functioning programming is the ideal way to program? – alex Jan 26 '16 at 07:59
  • AngularJS, Q promises, and Javascript itself are taking ideas (and benefiting) from functional programming concepts. If you want to know more, ask that as a question. – georgeawg Jan 26 '16 at 08:07

1 Answers1

7

You can do it like so:

var all = function() { return $q.all([service.getAllItems()]) }

var getItems = function() {
  return all().then(function(value) {
     $scope.list = JSON.parse(value)
  }, function(reason) {
    $scope.result = reason
  });
}

getItems().then(function() {
  // do stuff with $scope.list
}

If you return a promise in a function you can chain a .then to it, so now your getItems will return the promise from all(), once this is fulfilled your code will continue

Martijn Welker
  • 5,575
  • 1
  • 16
  • 26
  • @Hey it worked. Thanks! I'm just learning about promises. They are convenient but a bit hard to understand. – alex Jan 26 '16 at 07:46
  • No problem, just see it like this, as long as a function returns a promise you can chain a `.then` to it, when it returns a non-promise (result) your promise chain will be broken. – Martijn Welker Jan 26 '16 at 07:49
  • Thanks for explaining. Dang! Not enough reputation to upvote comments. – alex Jan 26 '16 at 07:54