DJWassink / Promise-parallel-throttle

It's kinda like Promise.all(), but throttled!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Throttle.all does not return T[] when failFast: false

jdbevan opened this issue · comments

When failFast is set to false when using Throttle.all you get a response type of Promise<(T | Error)[]>

See

import * as Throttle from "promise-parallel-throttle";

//Function which should return a Promise
const names = [
  { firstName: "Irene", lastName: "Pullman" },
  { firstName: "Sean", lastName: "Parr" },
  { firstName: "Joe", lastName: "Slater" },
  { firstName: "Karen", lastName: "Turner" },
  { firstName: "Tim", lastName: "Black" }
];

const combineNames = (firstName, lastName) => {
  return new Promise((resolve, reject) => {
    if (firstName === "Joe") {
      reject(new Error('Cannot have Joe'));
    } else {
      resolve(firstName + " " + lastName);
    }
  });
};

//Create a array of functions to be run
const tasks = names.map((u) => () => combineNames(u.firstName, u.lastName));

(async () => {
  try {
    const results = await Throttle.all(tasks, {
      maxInProgress: 1,
      failFast: false
    });
    console.info(results);
    // results here is ["Irene Pullman", "Sean Parr", Error, "Karen Turner", "Tim Black"]
  } catch (failed) {
    console.error(failed.message);
  }
})();

That's indeed so, if you only want the resolved tasks as a result I would suggest using the Throttle.raw as follows:

import * as Throttle from "promise-parallel-throttle";

//Function which should return a Promise
const names = [
  { firstName: "Irene", lastName: "Pullman" },
  { firstName: "Sean", lastName: "Parr" },
  { firstName: "Joe", lastName: "Slater" },
  { firstName: "Karen", lastName: "Turner" },
  { firstName: "Tim", lastName: "Black" }
];

const combineNames = (firstName, lastName) => {
  return new Promise((resolve, reject) => {
    if (firstName === "Joe") {
      reject(new Error('Cannot have Joe'));
    } else {
      resolve(firstName + " " + lastName);
    }
  });
};

//Create a array of functions to be run
const tasks = names.map((u) => () => combineNames(u.firstName, u.lastName));

(async () => {
  try {
    const results = await Throttle.raw(tasks, {
      maxInProgress: 1,
      failFast: false
    });
    console.info(results.resolvedIndexes.map(index => results.taskResults[index]));
    // ["Irene Pullman", "Sean Parr", "Karen Turner", "Tim Black"]
  } catch (failed) {
    console.error(failed.message);
  }
})();