Javascript AngularJS承诺,如何先$q.然后(其他[])

Javascript AngularJS承诺,如何先$q.然后(其他[]),javascript,angularjs,angular-promise,angularjs-q,Javascript,Angularjs,Angular Promise,Angularjs Q,在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

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

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

这与问题无关,但什么是
$scope.watch
?您的意思可能是
$scope.$watch
?在这种情况下,它不会返回一个承诺,而是一个注销侦听器。@Nikolajdallarsen那么,这就是你否决OP的原因?我不知道我没有投反对票,所以我不知道。我想让投反对票的人解释一下原因…那神奇的1000,500,1500是什么?如果第一个TAK超过1000毫秒呢?这些只是随机值,说明承诺可能在不同的时间完成。对$timeout的调用只是真正承诺的占位符。例如,在实际场景中,它可能是这样的:
var firstPromise=$http.get('/someurl')我现在更明白了。只是关于
$watch
的问题,是否可以等待
myParamount
的首次初始化(也可能是
myParamount2
),然后查询所有其他承诺?您应该将其作为单独的SO问题创建。我有一个办法来回答这个问题,但是在上面的答案中包含它并不合适。它有两个部分。1) 只开了一次$watch。2) 用承诺等待一块$watch。