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.
However i am stuck with angular 1.4 for now and need some kind of functionality like a $q.any
or $q.race
method.
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)
}
})
Question
I only need this to work for two promises at a time:
myRaceFkt(p1,p2)
.then(successcallback)
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(....
©2020 All rights reserved.