2017-07-28 69 views
0

在AngularJs控制器中,我需要确保在执行其他任务之前初始化一个极值变量。

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!"); 
}) 

如何解决这个“假”的代码?

+0

这与问题无关,但是'$ scope.watch'是什么?你可能是指'$ scope。$ watch'?在这种情况下,它不会返回一个承诺,而是一个取消注册的听众。 –

+0

@NikolajDamLarsen所以,这是你downvoted OP的原因?我不知道 – Serge

+0

我没有downvote所以我不知道。 –

回答

1

假设这些都是实际的承诺,你应该可以使用承诺链来做这样的事情。

这是一个使用超时用于说明目的的例子:

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; } } 

这就是一个办法链条他们,让对方承诺不运行,直到第一个解决了。

+0

什么是魔法1000,500,1500?如果第一次采集超过1000毫秒会怎么样? – Serge

+0

这些只是随机的值来说明承诺可能会在不同的时间完成。对$ timeout的调用只是实际承诺的占位符。例如,在一个真实的场景中,它可能看起来像这样:'var firstPromise = $ http.get('/ someurl');' –

+0

我现在明白了更好。只是关于'$ watch'的问题,是否可以等待myParamount(也可能是'myParamount2')的第一次初始化,然后查询所有其他的promise? – Serge