AngularJS:旧 Angular 版本中的 $q.race() [英] AngularJS: $q.race() in old angular versions
问题描述
Angular 1.5.8 实现了一个 $q.race()
方法,该方法接受一个 promise 数组并返回一个 promise,该 promise 使用第一个已解析的 promise 的值进行解析.
Angular 1.5.8 implements a $q.race()
method which takes an array of promises and returns a promise which is resolves with the value of the first resolved promise.
但是我现在坚持使用 angular 1.4,需要某种功能,例如 $q.any
或 $q.race
方法.
However i am stuck with angular 1.4 for now and need some kind of functionality like a $q.any
or $q.race
method.
目前我在 .then()
中使用标志来记住"明显不理想的承诺状态.
Currently I use flags inside .then()
to "remember" the state of promises which obviously is not ideal.
var resolvedPromise = null;
promise1.then(function(data){
if(!resolvedPromise === 'promise2'){
resolvedPromise = 'promise1';
successcallback(data)
}
})
promise2.then(function(data){
if(!resolvedPromise === 'promise1'){
resolvedPromise = 'promise2';
successcallback(data)
}
})
问题
我只需要一次为两个承诺工作:
I only need this to work for two promises at a time:
myRaceFkt(p1,p2)
.then(successcallback)
是否有更优雅的解决方案,而无需访问 1.5.8 改进的 $q
-api?
Is there a more elegant solution without having access to the improved $q
-api of 1.5.8?
推荐答案
function myRaceFn(promises){
return $q(function(resolve, reject) {
promises.forEach(function(promise) {
promise.then(resolve, reject);
});
});
}
myRaceFn([promise1, promise2]).then(....
这篇关于AngularJS:旧 Angular 版本中的 $q.race()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!