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       46x 46x 46x   46x 46x 130x 60x 60x     70x 70x   70x   65x 65x 65x 65x         46x 9x 9x     37x 65x         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;