I am trying to chain 3 promises. I find that if I resolve promise1, I get the result in the promise2's success callback and I can control what and if I need to send anything to promise3.
But if I issue a notify in promise1, not matter what I do in promise2, the promise3's notifyCallback ALWAYS get triggered immediately. How can I prevent it and make it conditional based on some business rules in promise2 ?
Here is a simple example in jsfiddle: http://jsfiddle.net/deepfiddle/rxv8322s/
If you issue .notify() instead of .resolve() (uncomment/comment the line in promise1), you will see what promise3 gets notified immediately. Here is the relevant code:
var myApp = angular.module('myApp', []);
myApp.controller('myCtrl', function($scope, $q, $timeout) {
console.log("--app controller");
var p0 = $q.when();
p0
.then( //Promise: p1
function(result) {
console.log("p1", result);
var deferred = $q.defer();
$timeout(function() {
console.log("in timeout of p1");
//Note1: Propagation of resolve can be controlled but not notify
// Uncomment notify instead to see the difference on the console
deferred.resolve("p1 resolved by timeout 2000");
//deferred.notify("p1 notified by timeout 2000");
}, 2000);
return deferred.promise;
}
)
.then(//Promise: p2
function(result) {
console.log("p2-onsuccess:", result);
var deferred = $q.defer();
$timeout(function() {
console.log("in timeout of p2");
deferred.resolve("p2 resolved by timeout 2000");
}, 2000);
return deferred.promise;
},
null,
function(result) {
//Note2: Unable to prevent propagation of p1.notify() to p3
console.log("p2-onnotify:", result);
var deferred = $q.defer();
$timeout(function() {
console.log("in timeout of p2");
deferred.notify("p2 notified by timeout 2000");
}, 2000);
return deferred.promise;
}
)
.then(//Promise:p3
function(result) {
console.log("p3-onsuccess:", result);
},
null,
function(result) {
console.log("p3-onnotify:", result);
}
)
});