gpt4 book ai didi

javascript - 无法通过嵌套 promise 获得 $q.all - 等待所有

转载 作者:行者123 更新时间:2023-11-29 16:48:52 26 4
gpt4 key购买 nike

我完全理解以前有人问过类似的问题,但我没有让它运行。我需要一个 promise 链,我需要等到所有 promise 都得到解决。

我的问题是我需要根据另一个 promise 的结果调用不同的 promise :-(

因此,根据 promise2 的结果,我的 promise4EITHER $translate.use OR 它是 $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
});

最佳答案

你真的不需要监控promise3promise4,你需要的只是promise1promise2 . promise3 成为 promise2 的下一步。只需注意如何从 promise2 然后部分返回新的 promise (return $translate.usereturn $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;
})
.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
});

关于javascript - 无法通过嵌套 promise 获得 $q.all - 等待所有,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38143838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com