es-promise-ext
Version:
Native promise extensions for javascript and typescript.
47 lines (46 loc) • 2.34 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = sequence;
function sequence(asyncFunctions, option) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
if (!Array.isArray(asyncFunctions)) {
throw new TypeError('Promise.sequence must be called with an array');
}
const canceller = (_a = option === null || option === void 0 ? void 0 : option.canceller) !== null && _a !== void 0 ? _a : {};
const progress = (_b = option === null || option === void 0 ? void 0 : option.progress) !== null && _b !== void 0 ? _b : function () { };
const skipIfError = (_c = option === null || option === void 0 ? void 0 : option.skipIfError) !== null && _c !== void 0 ? _c : false;
const result = [];
let step = 0;
for (let asyncFunction of asyncFunctions) {
if (canceller.cancelled === true) {
result.push(canceller);
progress(canceller, step++, asyncFunctions.length);
continue;
}
try {
const subResult = typeof asyncFunction === 'function' ? yield asyncFunction() : yield asyncFunction;
result.push(subResult);
progress(subResult, step++, asyncFunctions.length);
}
catch (error) {
if (skipIfError === true) {
result.push(error);
progress(error, step++, asyncFunctions.length);
}
else
throw error;
}
}
return result;
});
}