From 60c297d8e31690dbab7c8867023002c6ae2c11f6 Mon Sep 17 00:00:00 2001 From: tshemsedinov Date: Tue, 11 Jun 2019 02:16:26 +0300 Subject: [PATCH] Implement futurify callback-last to future-returning Closes: https://github.com/metarhia/metasync/issues/431 --- lib/adapters.js | 15 +++++++++++++++ test/future.js | 36 +++++++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 1 deletion(-) diff --git a/lib/adapters.js b/lib/adapters.js index 31c946dd..8857e1c6 100644 --- a/lib/adapters.js +++ b/lib/adapters.js @@ -1,5 +1,7 @@ 'use strict'; +const { Future } = require('./future'); + // Convert Promise to callback-last // promise // callback @@ -67,10 +69,23 @@ const promisifySync = fn => (...args) => { return Promise.resolve(result); }; +// Convert callback contract to Future-returning function +// fn callback-last function +// +// Returns: 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, }; diff --git a/test/future.js b/test/future.js index ba13dbfa..a056772d 100644 --- a/test/future.js +++ b/test/future.js @@ -1,6 +1,6 @@ 'use strict'; -const { Future } = require('..'); +const { Future, futurify } = require('..'); const metatests = require('metatests'); metatests.test('Future map/fork', async test => { @@ -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(); + }); +});