2021-02-04 19:15:23 +01:00
|
|
|
import promiseToCallback from 'promise-to-callback';
|
2020-01-09 04:34:58 +01:00
|
|
|
|
2019-11-20 01:03:20 +01:00
|
|
|
const callbackNoop = function (err) {
|
|
|
|
if (err) {
|
2021-02-04 19:15:23 +01:00
|
|
|
throw err;
|
2019-11-20 01:03:20 +01:00
|
|
|
}
|
2021-02-04 19:15:23 +01:00
|
|
|
};
|
2016-11-28 21:43:44 +01:00
|
|
|
|
2018-04-16 19:08:04 +02:00
|
|
|
/**
|
|
|
|
* A generator that returns a function which, when passed a promise, can treat that promise as a node style callback.
|
2018-04-17 01:53:29 +02:00
|
|
|
* The prime advantage being that callbacks are better for error handling.
|
2018-04-16 19:08:04 +02:00
|
|
|
*
|
2020-01-13 19:36:36 +01:00
|
|
|
* @param {Function} fn - The function to handle as a callback
|
|
|
|
* @param {Object} context - The context in which the fn is to be called, most often a this reference
|
2018-04-16 19:08:04 +02:00
|
|
|
*
|
|
|
|
*/
|
2020-11-03 00:41:28 +01:00
|
|
|
export default function nodeify(fn, context) {
|
2020-08-13 22:35:18 +02:00
|
|
|
return function (...args) {
|
2021-02-04 19:15:23 +01:00
|
|
|
const lastArg = args[args.length - 1];
|
|
|
|
const lastArgIsCallback = typeof lastArg === 'function';
|
|
|
|
let callback;
|
2017-10-06 21:36:08 +02:00
|
|
|
if (lastArgIsCallback) {
|
2021-02-04 19:15:23 +01:00
|
|
|
callback = lastArg;
|
|
|
|
args.pop();
|
2017-10-06 21:36:08 +02:00
|
|
|
} else {
|
2021-02-04 19:15:23 +01:00
|
|
|
callback = callbackNoop;
|
2017-10-06 21:36:08 +02:00
|
|
|
}
|
2019-03-29 05:37:40 +01:00
|
|
|
// call the provided function and ensure result is a promise
|
2021-02-04 19:15:23 +01:00
|
|
|
let result;
|
2019-03-29 05:37:40 +01:00
|
|
|
try {
|
2021-02-04 19:15:23 +01:00
|
|
|
result = Promise.resolve(fn.apply(context, args));
|
2019-03-29 05:37:40 +01:00
|
|
|
} catch (err) {
|
2021-02-04 19:15:23 +01:00
|
|
|
result = Promise.reject(err);
|
2019-03-29 05:37:40 +01:00
|
|
|
}
|
|
|
|
// wire up promise resolution to callback
|
2021-02-04 19:15:23 +01:00
|
|
|
promiseToCallback(result)(callback);
|
|
|
|
};
|
2016-11-28 21:43:44 +01:00
|
|
|
}
|