Reputation: 2559
I have demonstrated promise chaining where promise's p1,p2,p3 has to be resolved synchronously.
The code below is using angular.js 1, and here P3 is resolved then P2 and then P1.
the code is as follows,
<script type="text/javaScript">
angular.module("myApp",[]);
angular.module("myApp").controller("myCtrl",myCtrl);
angular.module("myApp").factory("demoService",demoService);
demoService.$inject = ["$q","$timeout"];
myCtrl.$inject = ["$scope","demoService"];
function myCtrl($scope,demoService){
var vm = this;
vm.init = init;
vm.myList = [];
function init(){
var p1 = demoService.get1000();
var p3 = demoService.get3000();
var p2 = demoService.get2000();
p3.then(function(obj){
console.log(obj.name);
return p2;
}).then(function(obj){
console.log(obj.name);
return p1;
}).then(function(obj){
console.log(obj.name);
});
} // end of init
} // end of myCtrl
function demoService($q,$timeout){
var obj = {};
obj.get1000 = get1000;
obj.get2000 = get2000;
obj.get3000 = get3000;
return obj;
function get1000(){
var deferred = $q.defer();
var INTERVAL = 1000;
$timeout(function() {
deferred.resolve({ "name" : INTERVAL });
}, INTERVAL);
return deferred.promise;
}
function get2000(){
var deferred = $q.defer();
var INTERVAL = 2000;
$timeout(function() {
deferred.resolve({ "name" : INTERVAL });
}, INTERVAL);
return deferred.promise;
}
function get3000(){
var deferred = $q.defer();
var INTERVAL = 3000;
$timeout(function() {
deferred.resolve({ "name" : INTERVAL });
}, INTERVAL);
return deferred.promise;
}
} // end of demoService
</script>
So, my question is, Is there any better way of doing the above operation ? Also please review my code. Thanks.
Upvotes: 0
Views: 62
Reputation: 1074238
where promise's p1,p2,p3 has to be resolved synchronously
Those promises will not be resolved synchronously, or serially (if that's what you meant).
A promise doesn't control the asynchronous action, it just represents the result. So by doing this:
var p1 = demoService.get1000();
var p3 = demoService.get3000();
var p2 = demoService.get2000();
...you've already started the actions, which will run in parallel (although in your case, as they all just schedule timer callbacks on the main thread, they'll get serialized by contention for that one thread).
If you want to do one thing, wait for it to finish, and then do the next (e.g., do them in series, aka serially), you build a chain:
demoService.get1000()
.then(result1 => demoService.get3000())
.then(result2 => demoService.get2000())
.then(result3 => {
// Do something with the result
})
.catch(error => {
// Do something with the error
});
Of course, if you want all three results at the end, you have to make result1
and result2
available to the third callback in any of several ways.
Upvotes: 2