我完全理解之前已经提出类似的问题,但我没有让它运行。我需要一系列承诺,我需要等到所有承诺都得到解决。
我的问题是我需要根据另一个承诺的结果来调用不同的承诺: - (
因此,基于 promise2 的结果,我的承诺4 是 EITHER $ translate.use 或 $ translate.refresh 。
这是我到目前为止(简化):
var promise1 = someService.get({}).$promise.then(function (result) {
// do stuff
});
var promise2 = anotherService.getPromise().then(function (result) {
var properties = result[0];
// do stuff
return properties;
});
var promise3 = promise2.then(function(properties){
// using $translate (angular-translate) here which is async as well
var userLanguage = properties.language;
if (userLanguage !== $translate.preferredLanguage()) {
// either this is the 4th promise
$translate.use(userLanguage).then(function (myVar) {
// ...
});
} else {
// or this is the 4th promise
$translate.refresh().then(function (myVar) {
// ...
});
}
});
var loadPromises = {
promise1: promise1
promise2: promise2
promise3: promise3
promise4: ???
};
$q.all(loadPromises).then(function (result) {
// anything done
});

答案 0 :(得分:4)
您并非真正需要监控promise3
和promise4
,您只需promise1
和promise2
。 promise3
成为promise2
的下一步。请注意您如何从return $translate.use
返回新承诺(return $translate.refresh
或promise2
),然后部分:
var promise1 = someService.get({}).$promise.then(function(result) {
// do stuff
});
var promise2 = anotherService.getPromise().then(function(result) {
var properties = result[0];
// do stuff
return properties;
})
.then(function(properties) {
// using $translate (angular-translate) here which is async as well
var userLanguage = properties.language;
if (userLanguage !== $translate.preferredLanguage()) {
// either this is the 4th promise
return $translate.use(userLanguage).then(function(myVar) {
// ...
});
} else {
// or this is the 4th promise
return $translate.refresh().then(function(myVar) {
// ...
});
}
});
var loadPromises = {
promise1: promise1,
promise2: promise2
};
$q.all(loadPromises).then(function(result) {
// anything done
});
答案 1 :(得分:1)
如果我对你的代码了解得足够好,我认为你只需要在promise3
内部返回内部承诺。在您的示例中,promise1
和promise2
都无法解决,直到服务完成。由于promise3
取决于promise2
,所以在promise2
解决之前它不会完成。我相信$q.all
会继续前进,直到所有承诺都完成,甚至是承诺所带来的承诺。由于promise3
会返回一个承诺,promise3
不会被视为已解决,直到内部承诺得到解决。所以,我认为只需要添加几个return
语句:
var promise1 = someService.get({}).$promise.then(function (result) {
// do stuff
});
var promise2 = anotherService.getPromise().then(function (result) {
var properties = result[0];
// do stuff
return properties;
});
var promise3 = promise2.then(function(properties){
// using $translate (angular-translate) here which is async as well
var userLanguage = properties.language;
if (userLanguage !== $translate.preferredLanguage()) {
// either this is the 4th promise
//NOTE: added return here
return $translate.use(userLanguage).then(function (myVar) {
// ...
});
} else {
// or this is the 4th promise
//NOTE: added return here
return $translate.refresh().then(function (myVar) {
// ...
});
}
});
var loadPromises = {
promise1: promise1,
promise2: promise2,
promise3: promise3
};
$q.all(loadPromises).then(function (result) {
// anything done
});