Folks,
I have my code setup somewhat as below:
$scope.init = function(){
return $q.all([resource1.query(),resource2.query(),resource3.query()])
.then(result){
$scope.data1 = result[1];
$scope.data2 = result1[2];
$scope.data3 = result[3];
console.log(data1); //prints as [$resolved: false, $then: function]
doSomething($scope.data1,$scope.data2);
}
}
I was under the impression that the "then" function will be called only when all the resources get resolved. However this is not what I am seeing in my code. If I print data1, I get unresolveed.
Any clue as to what I am missing here ??
$q is integrated with the $rootScope. Scope Scope model observation mechanism in AngularJS, which means faster propagation of resolution or rejection into your models and avoiding unnecessary browser repaints, which would result in flickering UI. Q has many more features than $q, but that comes at a cost of bytes.
$q. defer() allows you to create a promise object which you might want to return to the function that called your login function. Make sure you return deferred.
Overview. A factory which creates a resource object that lets you interact with RESTful server-side data sources. The returned resource object has action methods which provide high-level behaviors without the need to interact with the low level $http service. Requires the ngResource module to be installed.
Promises in AngularJS are provided by the built-in $q service. They provide a way to execute asynchronous functions in series by registering them with a promise object. {info} Promises have made their way into native JavaScript as part of the ES6 specification.
I ran into this problem, and it was quite confusing. The problem appears to be that calling a resource action doesn't actually return an http promise, but an empty reference (that is populated when the data returns from the server -see the return value section of the $resource docs).
I'm not sure why this results in .then(result) returning an array of unresolved promises, but to get each resource's promise, you need to use resource1.query().$promise
. To re-write your example:
$scope.init = function() {
return $q.all([resource1.query().$promise, resource2.query().$promise, resource3.query().$promise])
.then( function(result) {
$scope.data1 = result[0];
$scope.data2 = result[1];
$scope.data3 = result[2];
console.log($scope.data1);
doSomething($scope.data1,$scope.data2);
})
}
I hope that saves someone else some time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With