attempt-man
Version:
Beautifully manage attempts for your process!
88 lines (65 loc) • 2.9 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _attempt = require('./attempt');
var _attempt2 = _interopRequireDefault(_attempt);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var AttemptManager = function () {
/**
* Create a new AttemptManager.
*/
function AttemptManager() {
var maxAttempts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 3;
_classCallCheck(this, AttemptManager);
this.attempts = [];
this.maxAttempts = maxAttempts;
}
/**
* Run the attempt.
*/
_createClass(AttemptManager, [{
key: 'run',
value: function () {
var _ref = _asyncToGenerator(regeneratorRuntime.mark(function _callee(callback) {
var attempt, result;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (!(this.attempts.length <= this.maxAttempts)) {
_context.next = 8;
break;
}
attempt = new _attempt2.default();
_context.next = 4;
return attempt.run(callback);
case 4:
result = _context.sent;
if (!attempt.successful) {
_context.next = 7;
break;
}
return _context.abrupt('return', result);
case 7:
throw new Error('All attempts are failed.');
case 8:
case 'end':
return _context.stop();
}
}
}, _callee, this);
}));
function run(_x2) {
return _ref.apply(this, arguments);
}
return run;
}()
}]);
return AttemptManager;
}();
exports.default = AttemptManager;
module.exports = exports['default'];