diff options
Diffstat (limited to 'lib/asyncify.js')
-rw-r--r-- | lib/asyncify.js | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/lib/asyncify.js b/lib/asyncify.js new file mode 100644 index 0000000..f9f00e1 --- /dev/null +++ b/lib/asyncify.js @@ -0,0 +1,26 @@ +'use strict'; + +import isObject from 'lodash/isObject'; +import rest from 'lodash/rest'; + +export default function asyncify(func) { + return rest(function (args) { + var callback = args.pop(); + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (isObject(result) && typeof result.then === 'function') { + result.then(function(value) { + callback(null, value); + })['catch'](function(err) { + callback(err.message ? err : new Error(err)); + }); + } else { + callback(null, result); + } + }); +} |