promise-util-task
Version:
task manager for promise
70 lines (69 loc) • 2.25 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
/**
* It will always be executed in the order waiting for the result of Promise.
* @param funcs An array of functions that return value, or promise.
* @returns Results are stored in the order stored in funcs.
*/
exports.seq = function (funcs) {
var results = [];
return funcs.reduce(function (prevPromise, func) {
return prevPromise.then(function () {
return Promise.resolve(func()).then(function (value) {
results.push(value);
});
});
}, Promise.resolve()).then(function () { return results; });
};
/**
* Execute processing at once.
* @param funcs An array of functions that return value, or promise.
* @returns Results are stored in the order stored in funcs.
*/
exports.all = function (funcs) {
var promises = funcs.map(function (func) {
try {
return Promise.resolve(func());
}
catch (e) {
return Promise.reject(e);
}
});
return Promise.all(promises);
};
/**
* Execute the specified number of processes at once.
* @param funcs An array of functions that return value, or promise.
* @param max Maximum number of simultaneous executions.
* @returns Results are stored in the order stored in funcs.
*/
exports.limit = function (funcs, max) {
if (max === void 0) { max = 1; }
return exports.all(limit_preprocess(funcs, max)).
then(limit_postprocess);
};
var limit_preprocess = function (funcs, max) {
var pipeline = [];
for (var i = 0; i < max; ++i) {
pipeline[i] = [];
}
funcs.forEach(function (func, n) {
var idx = n % max;
pipeline[idx].push(func);
});
return pipeline.map(function (funcs) {
return function () { return exports.seq(funcs); };
});
};
var limit_postprocess = function (matrix) {
var max = matrix.reduce(function (sum, line) { return sum + line.length; }, 0);
var results = new Array(max);
var len = matrix.length;
for (var i = 0; i < len; ++i) {
var lenj = matrix[i].length;
for (var j = 0; j < lenj; ++j) {
results[i + (j * len)] = matrix[i][j];
}
}
return results;
};