wrapSync.js 3.7 KB

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