-3

I currently have this working JS code:

async (list) => {
        var peers = await Promise.allSettled(list);
        peers = peers.filter(peer => peer.status === "fulfilled");
        return Promise.all(peers);
    }

However, it plays havoc with Typescript's type system. What's the recommended way to do this?

Rillian Grant
  • 98
  • 1
  • 8
  • `Promise.allSettled` fulfills when all promises settle. If you're concerned about a single promise not settling in a timely fashion, you can put a timer on it. TJ Crowder shows an example here [NodeJS Timeout a Promise if failed to complete in time](https://stackoverflow.com/a/32461436/4797603) – Ronnie Royston Oct 28 '22 at 02:43
  • 2
    What do you mean by "*it plays havoc with Typescript's type system.*"? Your function has no type annotations so it's not clear what you expect. If you're getting a type error, please post it. – Bergi Oct 28 '22 at 02:57

1 Answers1

2

You can omit Promise.all() and just return the values from the fulfilled promises

const fulfill = async <T,>(list: Promise<T>[]): Promise<T[]> => {
  // Wait for all promises to complete then filter for "fulfilled"
  const fulfilled = (await Promise.allSettled(list)).filter(
    ({ status }) => status === "fulfilled"
  ) as PromiseFulfilledResult<T>[]; // this cast lets you access `.value`

  // Map out the `.value` properties
  return fulfilled.map(({ value }) => value);
};

There's no need for Promise.all() because your async function already returns a promise which you're resolving with an array produced by Promise.allSettled().

Using this will produce an array of successfully resolved values

const list: Promise<number>[] = [
  Promise.resolve(1),
  Promise.resolve(2),
  Promise.reject(3),
  Promise.resolve(5),
];

console.log(await fulfill(list)); // [1, 2, 5]

TypeScript Playground

Phil
  • 157,677
  • 23
  • 242
  • 245
  • This doesn't change the result from the OP's code as calling `Promise.all(peers)` just returns `peers` anyway. I agree that `Promise.all()` was not needed, but this doesn't fix/change the result. – jfriend00 Oct 28 '22 at 02:46
  • @jfriend00 OP is returning an array of `PromiseSettledResult`. I assumed from their comment _"plays havoc with Typescript's type system"_ that they'd rather the resolved values returned instead – Phil Oct 28 '22 at 02:56