Issue
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?
Solution
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]
Answered By - Phil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.