AngularJS:旧角度版本的$ 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.
但是我现在仍然坚持使用角度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)
是否有一个更优雅的解决方案,无法访问改进的 $ q
-api为1.5.8?
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:旧角度版本的$ q.race()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!