3 Object.defineProperty(exports, "__esModule", {
6 exports.default = asyncify;
8 var _isObject = require('lodash/isObject');
10 var _isObject2 = _interopRequireDefault(_isObject);
12 var _initialParams = require('./internal/initialParams');
14 var _initialParams2 = _interopRequireDefault(_initialParams);
16 function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
19 * Take a sync function and make it async, passing its return value to a
20 * callback. This is useful for plugging sync functions into a waterfall,
21 * series, or other async functions. Any arguments passed to the generated
22 * function will be passed to the wrapped function (except for the final
23 * callback argument). Errors thrown will be passed to the callback.
25 * If the function passed to `asyncify` returns a Promise, that promises's
26 * resolved/rejected state will be used to call the callback, rather than simply
27 * the synchronous return value.
29 * This also means you can asyncify ES2016 `async` functions.
33 * @memberOf module:Utils
37 * @param {Function} func - The synchronous function to convert to an
38 * asynchronous function.
39 * @returns {Function} An asynchronous wrapper of the `func`. To be invoked with
43 * // passing a regular synchronous function
45 * async.apply(fs.readFile, filename, "utf8"),
46 * async.asyncify(JSON.parse),
47 * function (data, next) {
48 * // data is the result of parsing the text.
49 * // If there was a parsing error, it would have been caught.
53 * // passing a function returning a promise
55 * async.apply(fs.readFile, filename, "utf8"),
56 * async.asyncify(function (contents) {
57 * return db.model.create(contents);
59 * function (model, next) {
60 * // `model` is the instantiated model object.
61 * // If there was an error, this function would be skipped.
66 * var q = async.queue(async.asyncify(async function(file) {
67 * var intermediateStep = await processFile(file);
68 * return await somePromise(intermediateStep)
73 function asyncify(func) {
74 return (0, _initialParams2.default)(function (args, callback) {
77 result = func.apply(this, args);
81 // if result is Promise object
82 if ((0, _isObject2.default)(result) && typeof result.then === 'function') {
83 result.then(function (value) {
84 callback(null, value);
86 callback(err.message ? err : new Error(err));
89 callback(null, result);
93 module.exports = exports['default'];