Skip to content

Commit

Permalink
Merge 7eebe3b into d76a7cd
Browse files Browse the repository at this point in the history
  • Loading branch information
gyson committed Aug 27, 2015
2 parents d76a7cd + 7eebe3b commit e3cfd2e
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 10 deletions.
37 changes: 27 additions & 10 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,29 @@ function Wrap(fn, ctx, next) {
this._fn = fn;
this._ctx = ctx;
this._next = next;
this._called = false;
this._value = undefined;
this._promise = undefined;
this._generator = undefined;
}

/**
* Lazily call the function.
* Note that if it's not an async or generator function,
* throws may mess things up.
*
* @returns {Mixed}
*/

Wrap.prototype._getValue = function () {
return this._fn.call(this._ctx, this._next);
if (!this._called) {
this._called = true;
try {
this._value = this._fn.call(this._ctx, this._next);
} catch (e) {
this._value = Promise.reject(e);
}
}
return this._value
};

/**
Expand All @@ -50,10 +61,13 @@ Wrap.prototype._getValue = function () {
*/

Wrap.prototype._getPromise = function () {
var value = this._getValue();
return isGenerator(value)
? co.call(this._ctx, value)
: Promise.resolve(value);
if (this._promise === undefined) {
var value = this._getValue();
this._promise = isGenerator(value)
? co.call(this._ctx, value)
: Promise.resolve(value);
}
return this._promise
}

/**
Expand All @@ -63,10 +77,13 @@ Wrap.prototype._getPromise = function () {
*/

Wrap.prototype._getGenerator = function () {
var value = this._getValue();
return isGenerator(value)
? value
: promiseToGenerator.call(this._ctx, value);
if (this._generator === undefined) {
var value = this._getValue();
this._generator = isGenerator(value)
? value
: promiseToGenerator.call(this._ctx, value);
}
return this._generator
}

/**
Expand Down
19 changes: 19 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,25 @@ it('should support delegating-yielding a random value', function () {
})
})

it('should support return another wrap', function (done) {
var i = 0
var stack = [
function (next) {
i++;
return next
},
function (next) {
i++;
return next
}
]

return compose(stack)().then(function () {
assert.equal(i, 2)
done()
})
})

it('should support an empty array', function () {
return compose([])().then(function () {

Expand Down

0 comments on commit e3cfd2e

Please sign in to comment.