AngularJS承诺,如何$q.first.then(others[])



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

如何修复此"假"代码?

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

下面是使用超时的示例,用于说明目的:

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

这是将它们链接起来的一种方法,因此在第一个承诺解决之前,其他承诺不会运行。