wrapSync.js 3.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. exports.default = asyncify;
  6. var _isObject = require('lodash/isObject');
  7. var _isObject2 = _interopRequireDefault(_isObject);
  8. var _initialParams = require('./internal/initialParams');
  9. var _initialParams2 = _interopRequireDefault(_initialParams);
  10. var _setImmediate = require('./internal/setImmediate');
  11. var _setImmediate2 = _interopRequireDefault(_setImmediate);
  12. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  13. /**
  14. * Take a sync function and make it async, passing its return value to a
  15. * callback. This is useful for plugging sync functions into a waterfall,
  16. * series, or other async functions. Any arguments passed to the generated
  17. * function will be passed to the wrapped function (except for the final
  18. * callback argument). Errors thrown will be passed to the callback.
  19. *
  20. * If the function passed to `asyncify` returns a Promise, that promises's
  21. * resolved/rejected state will be used to call the callback, rather than simply
  22. * the synchronous return value.
  23. *
  24. * This also means you can asyncify ES2017 `async` functions.
  25. *
  26. * @name asyncify
  27. * @static
  28. * @memberOf module:Utils
  29. * @method
  30. * @alias wrapSync
  31. * @category Util
  32. * @param {Function} func - The synchronous function, or Promise-returning
  33. * function to convert to an {@link AsyncFunction}.
  34. * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be
  35. * invoked with `(args..., callback)`.
  36. * @example
  37. *
  38. * // passing a regular synchronous function
  39. * async.waterfall([
  40. * async.apply(fs.readFile, filename, "utf8"),
  41. * async.asyncify(JSON.parse),
  42. * function (data, next) {
  43. * // data is the result of parsing the text.
  44. * // If there was a parsing error, it would have been caught.
  45. * }
  46. * ], callback);
  47. *
  48. * // passing a function returning a promise
  49. * async.waterfall([
  50. * async.apply(fs.readFile, filename, "utf8"),
  51. * async.asyncify(function (contents) {
  52. * return db.model.create(contents);
  53. * }),
  54. * function (model, next) {
  55. * // `model` is the instantiated model object.
  56. * // If there was an error, this function would be skipped.
  57. * }
  58. * ], callback);
  59. *
  60. * // es2017 example, though `asyncify` is not needed if your JS environment
  61. * // supports async functions out of the box
  62. * var q = async.queue(async.asyncify(async function(file) {
  63. * var intermediateStep = await processFile(file);
  64. * return await somePromise(intermediateStep)
  65. * }));
  66. *
  67. * q.push(files);
  68. */
  69. function asyncify(func) {
  70. return (0, _initialParams2.default)(function (args, callback) {
  71. var result;
  72. try {
  73. result = func.apply(this, args);
  74. } catch (e) {
  75. return callback(e);
  76. }
  77. // if result is Promise object
  78. if ((0, _isObject2.default)(result) && typeof result.then === 'function') {
  79. result.then(function (value) {
  80. invokeCallback(callback, null, value);
  81. }, function (err) {
  82. invokeCallback(callback, err.message ? err : new Error(err));
  83. });
  84. } else {
  85. callback(null, result);
  86. }
  87. });
  88. }
  89. function invokeCallback(callback, error, value) {
  90. try {
  91. callback(error, value);
  92. } catch (e) {
  93. (0, _setImmediate2.default)(rethrow, e);
  94. }
  95. }
  96. function rethrow(error) {
  97. throw error;
  98. }
  99. module.exports = exports['default'];