简体   繁体   English

角中的$ q.all()不能很好地解决

[英]$q.all() in angular does not resolve well

I am doing 3 $http calls in a factory and I am in troubles. 我在工厂做3 $ http电话,我遇到了麻烦。

I declare 4 promises: 我宣布了4个承诺:

var promise = $q.defer(),
  PBdeferred = $q.defer(),
  Rdeferred = $q.defer(),
  Pdeferred = $q.defer();

After that I do the first call to the API 之后,我第一次调用API

$http.get('/pendingBills').then(function(response) {
  var PendingBills = ['id', 'path', 'reservas', 'importe', 'fecha'];
  PBdeferred.resolve(PendingBills);
});

And for now resolve the last 2 promises with an empty array (I have not the endopoint yet) 现在用一个空数组解决最后2个promises(我还没有endopoint)

  Rdeferred.resolve([]);
  Pdeferred.resolve([]);

There is where I use $q.all 我在哪里使用$ q.all

$q.all([PBdeferred, Rdeferred, Pdeferred]).then(function (results){
    console.log('Results', results);
    promise.resolve({
      PendingBills: results[0],
      Remittances: results[1],
      Payed: results[2]
    });
  });

And return the higth level promise 并返回高级承诺

return promise.promise;

The console log shows the promises but I thougth that in there point the promises are resolved. 控制台日志显示了承诺,但我认为在那里承诺得到解决。

Some idea for fix this? 有什么想法解决这个问题?

You're not using $q.all correctly. 你没有正确使用$q.all It takes an array (or object) of promises, not an array of deferreds. 它需要一个promises的数组(或对象),而不是一个deferred数组。

Change 更改

$q.all([PBdeferred, Rdeferred, Pdeferred])

to

$q.all([PBdeferred.promise, Rdeferred.promise, Pdeferred.promise])

You are not using promises correctly, as you use deferred which is an anti pattern that breaks the promises chain. 你没有正确使用promises,因为你使用deferred这是一个打破promises链的反模式。 Instead of using deferred, just get the promise for each of your actions, then combine them using $q: 而不是使用延迟,只需获得每个操作的承诺,然后使用$ q组合它们:

var PBpromise = $http.get('/pendingBills').then(function(response) {
  return ['id', 'path', 'reservas', 'importe', 'fecha']; // this will return a promise with the array as the resolve value
});

var Rpromise = $q.resolve(); // a promise that is resolved immediately. Later you can replace it with the $http call 

var Ppromise = $q.resolve(); // a promise that is resolved immediately. Later you can replace it with the $http call 

var promise = $q.all([PBdpromise, Rpromise, Ppromise]).then(function (results){ // $q.all also returns a promise
    console.log('Results', results);
    return { // this will be the resolve value of the returned $q promise
      PendingBills: results[0],
      Remittances: results[1],
      Payed: results[2]
    };
  });

Note that $q.resolve() is only available since angular 1.4. 请注意, $q.resolve()仅在角度为1.4时可用。 If you use a prior version, use $q.when({}) instead of $q.resolve() . 如果您使用的是先前版本,请使用$q.when({})而不是$q.resolve()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM