UNPKG

1.32 kBJavaScriptView Raw
1import { FUN } from '@typen/enum-data-types';
2
3/**
4 * @typedef {Function|function(*,*[]):Promise<*[]>} AsyncService
5 *
6 * @param {*[]} freeAgentPool - array of functions or array of objects/classes. if latter case, a function must be provided as 'this'
7 * @param {*[]} clients
8 * @return {Promise<*[]>}
9 */
10
11async function promiseLobby(freeAgentPool, clients) {
12 /** @type {?AsyncService} */
13 const service = typeof this === FUN ? this : null;
14 const operationPool = [],
15 postOperationPool = new Set();
16
17 for (const client of clients) {
18 if (!freeAgentPool.length) await Promise.race(postOperationPool);
19 const busyAgent = freeAgentPool.shift();
20 const operation = Promise.resolve().then(service ? service.bind(busyAgent, client) : async () => await busyAgent(client));
21 operationPool.push(operation);
22 const postOperation = operation.then(() => {
23 postOperationPool.delete(postOperation);
24 freeAgentPool.push(busyAgent);
25 return busyAgent;
26 });
27 postOperationPool.add(postOperation); // Xr()
28 // ['freeAgent'](busyAgent|> deco)
29 // ['agentPool'](agentPool |> deco)
30 // ['busyAgent'](busyOperation|> deco)
31 // ['busyAgentPool'](busyOperationPool |> deco)
32 // |> says['asyncPool']
33 }
34
35 return Promise.all(operationPool);
36}
37
38export { promiseLobby };