-1

In an AngularJs controller I need to ensure a paramount variable initialized before performing other tasks.

var firstPromise = $scope.watch("myParamount"...); // from ng-init
var otherPromises = []; // once obtained myParamount, do others

// something like this?!
$q.firstPromise.then.all(otherPromises).then(function(){
    console.log("first, then otherPromises completed!");
})

How to fix this "fake" code?

serge
  • 13,940
  • 35
  • 121
  • 205

1 Answers1

1

Assuming those are actual promises, you should be able to use promise chaining to do something like this.

Here's a sample using timeouts for illustrative purposes:

var firstPromise = $timeout(echo('first'), 1000);

firstPromise.then(function(data){
    console.log(data); // 'first'
    return $q.all([  // Other promises
        $timeout(echo('other 1'), 1000),
        $timeout(echo('other 2'), 500),
        $timeout(echo('other 3'), 1500)
    ]);;
}).then(function(data){
    console.log(data); // ['other 1', 'other 2', 'other 3']
});

function echo(v) { return function(){ return v; } }

That is one way to chain them, so the other promises isn't run until the first has resolved.

Nikolaj Dam Larsen
  • 5,455
  • 4
  • 32
  • 45
  • what are that magic 1000, 500, 1500? what if the first taks take more than 1000ms? – serge Jul 28 '17 at 12:24
  • Those are just random values to illustrate that the promises might finish at different times. The calls to $timeout is just placeholders for real promises. So for instance in a real scenario it might look like this: `var firstPromise = $http.get('/someurl');` – Nikolaj Dam Larsen Jul 28 '17 at 12:45
  • I understand now better. Just question about `$watch`, is it possible to wait for the first initialization of `myParamount` (maybe also `myParamount2`), then query all other promises? – serge Jul 28 '17 at 12:55
  • You ought to create that as a separate SO question. I have an idea how to answer it, but it wouldn't really be fitting to include it in the answer above. There's two parts to it. 1) Only firing a $watch once. 2) awaiting a $watch using a promise. – Nikolaj Dam Larsen Jul 28 '17 at 13:07