Skip to content

Commit

Permalink
add promote function and tests
Browse files Browse the repository at this point in the history
  • Loading branch information
benperez committed May 29, 2015
1 parent 1d1df42 commit 871919d
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,13 @@ const readAndWrite = oath.co(function*(suffix) {

readAndWrite('foo').then(console.log, console.err);
```
### promote
```javascript
const fs = require('fs');

const readFile = oath.promote(fs.readFile);

readFile('foo.txt', {encoding: 'utf8'})
.then(filecontents => console.log('Here is foo.txt: ', filecontents))
.catch(error => console.error('Got an error!', error));
```
20 changes: 20 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,23 @@ exports.co = function(generator) {
});
});
};

// promote :: (a -> (Error -> b -> ()) -> ()) -> (a -> Promise b)
exports.promote = function(nodeFunction) {
return arity(nodeFunction.length - 1, () => {
const $functionArgs = arguments;
return new Promise((resolve, reject) => {
Array.prototype.push.call(
$functionArgs,
error => {
if (error != null) {
reject(error);
} else {
resolve.apply(null, Array.prototype.slice.call(arguments, 1));
}
}
);
nodeFunction.apply(null, $functionArgs);
});
});
};
49 changes: 49 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,3 +75,52 @@ describe('co', () => {
});
});
});

describe('promote', () => {
it('returns a function with the appropriate length', () => {
const f = oath.promote(callback => {
setTimeout(() => {
callback(null, 'foo');
}, 100);
});
assert.strictEqual(f.length, 0);
const g = oath.promote((a, callback) => {
setTimeout(() => {
callback(null, a);
}, 100);
});
assert.strictEqual(g.length, 1);
const h = oath.promote((a, b, callback) => {
setTimeout(() => {
callback(null, a, b);
}, 100);
});
assert.strictEqual(h.length, 2);
});

it('returns a function which returns a promise', () => {
const f = oath.promote(callback => {
setTimeout(() => {
callback(null, 'foo');
}, 100);
});
const p = f();
assert(p instanceof Promise);
});

it('returns a function which returns a promise for a value', (done) => {
const f = oath.promote(callback => {
setImmediate(() => {
callback(null, 'foo');
});
});
const p = f();
assert(p instanceof Promise);
p.then(value => {
assert.strictEqual(value, 'foo');
done();
}, () => {
assert.fail();
}).catch(err => console.err(err));
});
});

0 comments on commit 871919d

Please sign in to comment.