Use same lock values as mobile clients
[ProtonMail-WebClient.git] / packages / shared / lib / helpers / runInQueue.ts
blobe393d18f9e5b5b21607d921b3e386d3908f6a17c
1 /**
2  *  Executes functions sequentially, at most `maxProcessing` functions at once.
3  */
4 async function runInQueue<T>(functions: (() => Promise<T>)[], maxProcessing = 1): Promise<T[]> {
5     const results: T[] = [];
6     let resultIndex = 0;
8     const runNext = async (): Promise<any> => {
9         const index = resultIndex;
10         const executor = functions[index];
12         if (executor) {
13             resultIndex += 1;
14             return executor().then((result) => {
15                 results[index] = result;
16                 return runNext();
17             });
18         }
19         return Promise.resolve();
20     };
22     const promises: Promise<any>[] = [];
23     for (let i = 0; i < maxProcessing; i++) {
24         promises.push(runNext());
25     }
26     await Promise.all(promises);
27     return results;
30 export default runInQueue;