UNPKG

@minimaltech/node-infra

Version:

Minimal Technology NodeJS Infrastructure - Loopback 4 Framework

50 lines 2.06 kB
"use strict"; 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.executePromiseWithLimit = void 0; /** * Execute all tasks with limit number of asyncronous tasks. * Whenever 1 task's resolved next task will be executed. * * @example * With 20 tasks need to execute with limit is 5 tasks asyncronous * ``` * const tasks = <Array of 20 functions which return promises> * await executePromiseWithLimit({ * tasks, * limit: 5, onTaskDone: (opts: { result: any }) => { // Do something on task done }, * }) * ``` */ const executePromiseWithLimit = (opts) => __awaiter(void 0, void 0, void 0, function* () { const { tasks, limit, onTaskDone } = opts; const results = []; const executing = new Set(); for (const task of tasks) { const promise = task().then(result => { executing.delete(promise); return result; }); executing.add(promise); results.push(promise); if (executing.size >= limit) { const done = yield Promise.race(executing); onTaskDone === null || onTaskDone === void 0 ? void 0 : onTaskDone({ result: done }); } } yield Promise.all(executing); return Promise.all(results); }); exports.executePromiseWithLimit = executePromiseWithLimit; //# sourceMappingURL=promise.utility.js.map