From 2a5c3555829da51f55abd810a828c73b420316d3 Mon Sep 17 00:00:00 2001 From: Caio Cunha Date: Sun, 24 Mar 2013 22:18:10 -0300 Subject: feat($q): added support to promise notification It is now possible to notify a promise through deferred.notify() method. Notifications are useful to provide a way to send progress information to promise holders. --- src/ng/q.js | 48 ++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 42 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/ng/q.js b/src/ng/q.js index 994ecd8d..fe05b37f 100644 --- a/src/ng/q.js +++ b/src/ng/q.js @@ -199,7 +199,7 @@ function qFactory(nextTick, exceptionHandler) { var callback; for (var i = 0, ii = callbacks.length; i < ii; i++) { callback = callbacks[i]; - value.then(callback[0], callback[1]); + value.then(callback[0], callback[1], callback[2]); } }); } @@ -212,8 +212,25 @@ function qFactory(nextTick, exceptionHandler) { }, + notify: function(progress) { + if (pending) { + var callbacks = pending; + + if (pending.length) { + nextTick(function() { + var callback; + for (var i = 0, ii = callbacks.length; i < ii; i++) { + callback = callbacks[i]; + callback[2](progress); + } + }); + } + } + }, + + promise: { - then: function(callback, errback) { + then: function(callback, errback, progressback) { var result = defer(); var wrappedCallback = function(value) { @@ -234,10 +251,18 @@ function qFactory(nextTick, exceptionHandler) { } }; + var wrappedProgressback = function(progress) { + try { + result.notify((progressback || defaultCallback)(progress)); + } catch(e) { + exceptionHandler(e); + } + }; + if (pending) { - pending.push([wrappedCallback, wrappedErrback]); + pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]); } else { - value.then(wrappedCallback, wrappedErrback); + value.then(wrappedCallback, wrappedErrback, wrappedProgressback); } return result.promise; @@ -359,7 +384,7 @@ function qFactory(nextTick, exceptionHandler) { * @param {*} value Value or a promise * @returns {Promise} Returns a promise of the passed value or promise */ - var when = function(value, callback, errback) { + var when = function(value, callback, errback, progressback) { var result = defer(), done; @@ -381,15 +406,26 @@ function qFactory(nextTick, exceptionHandler) { } }; + var wrappedProgressback = function(progress) { + try { + return (progressback || defaultCallback)(progress); + } catch (e) { + exceptionHandler(e); + } + }; + nextTick(function() { ref(value).then(function(value) { if (done) return; done = true; - result.resolve(ref(value).then(wrappedCallback, wrappedErrback)); + result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback)); }, function(reason) { if (done) return; done = true; result.resolve(wrappedErrback(reason)); + }, function(progress) { + if (done) return; + result.notify(wrappedProgressback(progress)); }); }); -- cgit v1.2.3