From a2836fbb56cd10259a90ee125938e7cda4ab13c1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20Bajto=C5=A1?= Date: Tue, 17 Feb 2015 17:31:42 +0100 Subject: [PATCH] ModelBaseClass: support promise-based observers Allow the observer functions passed to `ModelBaseClass.observe` to return a promise instead of calling the callback. --- lib/model.js | 10 +++++++++- package.json | 1 + test/async-observer.test.js | 22 ++++++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/model.js b/lib/model.js index dadb722d..0a3ca8c0 100644 --- a/lib/model.js +++ b/lib/model.js @@ -567,7 +567,15 @@ ModelBaseClass.notifyObserversOf = function(operation, context, callback) { async.eachSeries( observers, - function(fn, next) { fn(context, next); }, + function notifySingleObserver(fn, next) { + var retval = fn(context, next); + if (retval && typeof retval.then === 'function') { + retval.then( + function() { next(); }, + next // error handler + ); + } + }, function(err) { callback(err, context) } ); }); diff --git a/package.json b/package.json index 6d0a6d03..e4a7091e 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "node >= 0.6" ], "devDependencies": { + "bluebird": "^2.9.9", "mocha": "^2.1.0", "should": "^5.0.0" }, diff --git a/test/async-observer.test.js b/test/async-observer.test.js index 32040018..47b32324 100644 --- a/test/async-observer.test.js +++ b/test/async-observer.test.js @@ -1,5 +1,6 @@ var ModelBuilder = require('../').ModelBuilder; var should = require('./init'); +var Promise = global.Promise || require('bluebird'); describe('async observer', function() { var TestModel; @@ -93,6 +94,27 @@ describe('async observer', function() { done(); }); }); + + it('resolves promises returned by observers', function(done) { + TestModel.observe('event', function(ctx) { + return Promise.resolve('value-to-ignore'); + }); + TestModel.notifyObserversOf('event', {}, function(err, ctx) { + // the test times out when the promises are not supported + done(); + }); + }); + + it('handles rejected promise returned by an observer', function(done) { + var testError = new Error('expected test error'); + TestModel.observe('event', function(ctx) { + return Promise.reject(testError); + }); + TestModel.notifyObserversOf('event', {}, function(err, ctx) { + err.should.eql(testError); + done(); + }); + }); }); function pushAndNext(array, value) {