javascript - $q.all() in angular does not resolve well -
i doing 3 $http calls in factory , in troubles.
i declare 4 promises:
var promise = $q.defer(), pbdeferred = $q.defer(), rdeferred = $q.defer(), pdeferred = $q.defer();
after first call api
$http.get('/pendingbills').then(function(response) { var pendingbills = ['id', 'path', 'reservas', 'importe', 'fecha']; pbdeferred.resolve(pendingbills); });
and resolve last 2 promises empty array (i have not endopoint yet)
rdeferred.resolve([]); pdeferred.resolve([]);
there use $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 higth level promise
return promise.promise;
the console log shows promises thougth in there point promises resolved.
some idea fix this?
you not using promises correctly, use deferred anti pattern breaks promises chain. instead of using deferred, promise each of actions, combine them using $q:
var pbpromise = $http.get('/pendingbills').then(function(response) { return ['id', 'path', 'reservas', 'importe', 'fecha']; // return promise array resolve value }); var rpromise = $q.resolve(); // promise resolved immediately. later can replace $http call var ppromise = $q.resolve(); // promise resolved immediately. later can replace $http call var promise = $q.all([pbdpromise, rpromise, ppromise]).then(function (results){ // $q.all returns promise console.log('results', results); return { // resolve value of returned $q promise pendingbills: results[0], remittances: results[1], payed: results[2] }; });
note $q.resolve()
available since angular 1.4. if use prior version, use $q.when({})
instead of $q.resolve()
.
Comments
Post a Comment