diff --git a/lib/ChainFind.js b/lib/ChainFind.js index 18760205..7edaba9e 100644 --- a/lib/ChainFind.js +++ b/lib/ChainFind.js @@ -1,10 +1,12 @@ var _ = require("lodash"); var Singleton = require("./Singleton"); var ChainInstance = require("./ChainInstance"); +var Promise = require("./Promise").Promise; module.exports = ChainFind; function ChainFind(Model, opts) { + var promise = null; var chain = { find: function () { var cb = null; @@ -110,6 +112,20 @@ function ChainFind(Model, opts) { run: function (cb) { return this.all(cb); }, + success: function (cb) { + if (!promise) { + promise = new Promise(); + promise.handle(this.all); + } + return promise.success(cb); + }, + fail: function (cb) { + if (!promise) { + promise = new Promise(); + promise.handle(this.all); + } + return promise.fail(cb); + }, all: function (cb) { opts.driver.find(opts.only, opts.table, opts.conditions, { limit : opts.limit, diff --git a/lib/Promise.js b/lib/Promise.js new file mode 100644 index 00000000..0008adea --- /dev/null +++ b/lib/Promise.js @@ -0,0 +1,30 @@ +exports.Promise = Promise; + +function Promise(opts) { + opts = opts || {}; + + var success_cb = opts.success || null; + var fail_cb = opts.fail || null; + + return { + handle: function (promise) { + promise(function (err) { + if (err) { + if (fail_cb) fail_cb(err); + } else { + var args = Array.prototype.slice.call(arguments, 1); + + if (success_cb) success_cb.apply(null, args); + } + }); + }, + success: function (cb) { + success_cb = cb; + return this; + }, + fail: function (cb) { + fail_cb = cb; + return this; + } + }; +} diff --git a/test/integration/model-find-chain.js b/test/integration/model-find-chain.js index 5f5cf9aa..53b335da 100644 --- a/test/integration/model-find-chain.js +++ b/test/integration/model-find-chain.js @@ -461,4 +461,32 @@ describe("Model.find() chaining", function() { }); }); }); + + describe(".success()", function () { + before(setup()); + + it("should return a Promise with .fail() method", function (done) { + Person.find().success(function (people) { + should(Array.isArray(people)); + + return done(); + }).fail(function (err) { + // never called.. + }); + }); + }); + + describe(".fail()", function () { + before(setup()); + + it("should return a Promise with .success() method", function (done) { + Person.find().fail(function (err) { + // never called.. + }).success(function (people) { + should(Array.isArray(people)); + + return done(); + }); + }); + }); });