Skip to content

Commit

Permalink
Adds .success() and .fail() to ChainFind (#316)
Browse files Browse the repository at this point in the history
This is just an initial code, we should improve in the future and make
more parts of the code use the "Promise" (like Model.get)
  • Loading branch information
dresende committed Aug 26, 2013
1 parent 10d1d0f commit d014b37
Show file tree
Hide file tree
Showing 3 changed files with 74 additions and 0 deletions.
16 changes: 16 additions & 0 deletions lib/ChainFind.js
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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,
Expand Down
30 changes: 30 additions & 0 deletions lib/Promise.js
Original file line number Diff line number Diff line change
@@ -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;
}
};
}
28 changes: 28 additions & 0 deletions test/integration/model-find-chain.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
});
});
});

0 comments on commit d014b37

Please sign in to comment.