javascript - Angularjs chaining promises: propagation of notify vs resolve -
i trying chain 3 promises. find if resolve promise1, result in promise2's success callback , can control what , if need send promise3.
if issue notify in promise1, not matter in promise2, promise3's notifycallback triggered immediately. how can prevent , make conditional based on business rules in promise2 ?
here simple example in jsfiddle: http://jsfiddle.net/deepfiddle/rxv8322s/
if issue .notify() instead of .resolve() (uncomment/comment line in promise1), see promise3 gets notified immediately. here 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 controlled not notify // uncomment notify instead see difference on console deferred.resolve("p1 resolved timeout 2000"); //deferred.notify("p1 notified 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 timeout 2000"); }, 2000); return deferred.promise; }, null, function(result) { //note2: unable prevent propagation of p1.notify() p3 console.log("p2-onnotify:", result); var deferred = $q.defer(); $timeout(function() { console.log("in timeout of p2"); deferred.notify("p2 notified timeout 2000"); }, 2000); return deferred.promise; } ) .then(//promise:p3 function(result) { console.log("p3-onsuccess:", result); }, null, function(result) { console.log("p3-onnotify:", result); } ) });
Comments
Post a Comment