DJWassink / Promise-parallel-throttle

It's kinda like Promise.all(), but throttled!
MIT License
81 stars 3 forks source link

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

Closed jdbevan closed 2 years ago

jdbevan commented 2 years ago

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);
  }
})();
DJWassink commented 2 years ago

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);
  }
})();