AngularJS: $q.race() in old angular versions

ぃ、小莉子 提交于 2019-12-02 15:21:40

问题


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?


回答1:


function myRaceFn(promises){
   return $q(function(resolve, reject) { 
     promises.forEach(function(promise) {
       promise.then(resolve, reject);
     });
   });
}
myRaceFn([promise1, promise2]).then(....


来源:https://stackoverflow.com/questions/39489360/angularjs-q-race-in-old-angular-versions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!