tryEach.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. Object.defineProperty(exports, "__esModule", {
  3. value: true
  4. });
  5. var _eachSeries = require('./eachSeries.js');
  6. var _eachSeries2 = _interopRequireDefault(_eachSeries);
  7. var _wrapAsync = require('./internal/wrapAsync.js');
  8. var _wrapAsync2 = _interopRequireDefault(_wrapAsync);
  9. var _awaitify = require('./internal/awaitify.js');
  10. var _awaitify2 = _interopRequireDefault(_awaitify);
  11. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  12. /**
  13. * It runs each task in series but stops whenever any of the functions were
  14. * successful. If one of the tasks were successful, the `callback` will be
  15. * passed the result of the successful task. If all tasks fail, the callback
  16. * will be passed the error and result (if any) of the final attempt.
  17. *
  18. * @name tryEach
  19. * @static
  20. * @memberOf module:ControlFlow
  21. * @method
  22. * @category Control Flow
  23. * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to
  24. * run, each function is passed a `callback(err, result)` it must call on
  25. * completion with an error `err` (which can be `null`) and an optional `result`
  26. * value.
  27. * @param {Function} [callback] - An optional callback which is called when one
  28. * of the tasks has succeeded, or all have failed. It receives the `err` and
  29. * `result` arguments of the last attempt at completing the `task`. Invoked with
  30. * (err, results).
  31. * @returns {Promise} a promise, if no callback is passed
  32. * @example
  33. * async.tryEach([
  34. * function getDataFromFirstWebsite(callback) {
  35. * // Try getting the data from the first website
  36. * callback(err, data);
  37. * },
  38. * function getDataFromSecondWebsite(callback) {
  39. * // First website failed,
  40. * // Try getting the data from the backup website
  41. * callback(err, data);
  42. * }
  43. * ],
  44. * // optional callback
  45. * function(err, results) {
  46. * Now do something with the data.
  47. * });
  48. *
  49. */
  50. function tryEach(tasks, callback) {
  51. var error = null;
  52. var result;
  53. return (0, _eachSeries2.default)(tasks, (task, taskCb) => {
  54. (0, _wrapAsync2.default)(task)((err, ...args) => {
  55. if (err === false) return taskCb(err);
  56. if (args.length < 2) {
  57. [result] = args;
  58. } else {
  59. result = args;
  60. }
  61. error = err;
  62. taskCb(err ? null : {});
  63. });
  64. }, () => callback(error, result));
  65. }
  66. exports.default = (0, _awaitify2.default)(tryEach);
  67. module.exports = exports['default'];