Angularjs链接承诺:传播通知与解决

时间:2015-04-25 19:26:49

标签: javascript angularjs promise chaining

我正在尝试连锁3个承诺。我发现如果我解决了promise1,我会在promise2的成功回调中得到结果,我可以控制什么,如果我需要向promise3发送任何内容。
但是如果我在promise1中发出一个通知,不管我在promise2中做了什么,promise3的notifyCallback总是立即被触发。如何根据promise2中的某些业务规则来阻止它并使其成为条件?

以下是jsfiddle中的一个简单示例:http://jsfiddle.net/deepfiddle/rxv8322s/

如果发出.notify()而不是.resolve()(取消注释/注释promise1中的行),您将看到promise3立即得到通知。 以下是相关代码:

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);            
    }
)
});

0 个答案:

没有答案