UNPKG

cwait

Version:

Limit number of promises running in parallel

44 lines (43 loc) 1.52 kB
// This file is part of cwait, copyright (c) 2015- BusFaster Ltd. // Released under the MIT license, see LICENSE. /** Call func and return a promise for its result. * Optionally call given resolve or reject handler when the promise settles. */ export function tryFinally(func, onFinish, Promise, resolve, reject) { var promise; try { promise = Promise.resolve(func()); } catch (err) { // If func threw an error, return a rejected promise. promise = Promise.reject(err); } promise.then(onFinish, onFinish); if (resolve) promise.then(resolve, reject); return (promise); } /** Task wraps a promise, delaying it until some resource gets less busy. */ var Task = /** @class */ (function () { function Task(func, Promise, stamp) { this.func = func; this.Promise = Promise; this.stamp = stamp; } /** Wrap task result in a new promise so it can be resolved later. */ Task.prototype.delay = function () { var _this = this; if (!this.promise) { this.promise = new this.Promise(function (resolve, reject) { _this.resolve = resolve; _this.reject = reject; }); } return (this.promise); }; /** Start the task and call onFinish when done. */ Task.prototype.resume = function (onFinish) { return (tryFinally(this.func, onFinish, this.Promise, this.resolve, this.reject)); }; return Task; }()); export { Task };