es-promise-ext
Version:
Native promise extensions for javascript and typescript.
38 lines (37 loc) • 2.05 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 = reduce;
;
function reduce(asyncFunctions, option) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b, _c;
if (!Array.isArray(asyncFunctions)) {
throw new TypeError('Promise.reduce must be called with an async function 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 initValue = (_c = option === null || option === void 0 ? void 0 : option.initValue) !== null && _c !== void 0 ? _c : undefined;
let step = 0;
let result = initValue;
for (let asyncFunction of asyncFunctions) {
if (canceller.cancelled === true) {
progress(canceller, step++, asyncFunctions.length);
continue;
}
if (typeof asyncFunction !== 'function')
throw new TypeError('Promise.reduce must be called with an async function array');
result = yield asyncFunction(result);
progress(result, step++, asyncFunctions.length);
}
return result;
});
}