Skip to content

Commit

Permalink
Implement futurify callback-last to future-returning
Browse files Browse the repository at this point in the history
Closes: #431
  • Loading branch information
tshemsedinov committed Jun 11, 2019
1 parent 71c1a9b commit 65ec4dc
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
15 changes: 15 additions & 0 deletions lib/adapters.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

const { Future } = require('./future');

// Convert Promise to callback-last
// promise <Promise>
// callback <Function>
Expand Down Expand Up @@ -67,10 +69,23 @@ const promisifySync = fn => (...args) => {
return Promise.resolve(result);
};

// Convert callback contract to Future-returning function
// fn <Function> callback-last function
//
// Returns: <Function> Future-returning function
const futurify = fn => (...args) =>
new Future((resolve, reject) => {
fn(...args, (err, data) => {
if (err) reject(err);
else resolve(data);
});
});

module.exports = {
callbackify,
asyncify,
promiseToCallbackLast,
promisify,
promisifySync,
futurify,
};
36 changes: 35 additions & 1 deletion test/future.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const { Future } = require('..');
const { Future, futurify } = require('..');
const metatests = require('metatests');

metatests.test('Future map/fork', async test => {
Expand Down Expand Up @@ -90,3 +90,37 @@ metatests.test('Future stateless', async test => {

test.end();
});

metatests.test('Future futurify success', async test => {
const f1 = (a, b, callback) => {
if (typeof a !== 'number' || typeof b !== 'number') {
callback(new Error('Arguments must be numbers'));
return;
}
callback(null, a + b);
};

const f2 = futurify(f1);

f2(10, 20).fork(value => {
test.strictSame(value, 30);
test.end();
});
});

metatests.test('Future futurify fail', async test => {
const f1 = (a, b, callback) => {
if (typeof a !== 'number' || typeof b !== 'number') {
callback(new Error('Arguments must be numbers'));
return;
}
callback(null, a + b);
};

const f2 = futurify(f1);

f2('10', '20').fork(test.mustNotCall, error => {
test.strictSame(error.message, 'Arguments must be numbers');
test.end();
});
});

0 comments on commit 65ec4dc

Please sign in to comment.