All files / src/lib/helpers promiseLimit.ts

100% Statements 25/25
100% Branches 8/8
100% Functions 4/4
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 416x       40x 40x 40x   40x 40x 118x 54x 54x     64x 64x   64x   59x 59x 59x 59x         40x 9x 9x     31x 59x         6x  
const promiseLimit = async <T>(
  n: number,
  list: Array<() => Promise<T>>,
): Promise<T[]> => {
  const results: T[] = new Array(list.length);
  let nextIndex = 0;
  let active = 0;
 
  return new Promise<T[]>((resolve, reject) => {
    const runNext = () => {
      if (nextIndex >= list.length) {
        if (active === 0) resolve(results);
        return;
      }
 
      const current = nextIndex++;
      active++;
 
      list[current]()
        .then((value) => {
          results[current] = value;
          active--;
          runNext();
          if (active === 0 && nextIndex >= list.length) resolve(results);
        })
        .catch(reject);
    };
 
    if (list.length === 0) {
      resolve(results);
      return;
    }
 
    for (let i = 0; i < n && i < list.length; i++) {
      runNext();
    }
  });
};
 
export default promiseLimit;