Stretch0
Stretch0

Reputation: 9241

How to use promise.allSettled with typescript?

Typescript build is failing as it does not seem to like Promise.allSetttled even though I have set ts config comilerOptions with "lib": [ "ES2020.Promise" ],

It seems as though the response for promise.allSettled does not include result or reason.

When running typescript build I get the following error:

Property 'reason' does not exist on type 'PromiseSettledResult<IMyPromiseResult>'.

and

Property 'value' does not exist on type 'PromiseRejectedResult'.

My code block looks like this and as you can see, I am trying to access reason and result from eaech of the promises that get resolved.

const myPromise = async () : Promise<IMyPromiseResult> {
  return new Promise((resolve) => {
    resolve("hello world")
  })
}

const data = await Promise.allSettled([
  myPromise()
]);

const response = data.find(res => res.status === 'fulfilled')?.result;

if(!response) {
  const error = data.find(res => res.status === 'rejected')?.reason;
  throw new Error(error);
}

How can I update the Promise.allSettled declaration to include the correct interfaces?

Upvotes: 54

Views: 53660

Answers (6)

Kabir Sarin
Kabir Sarin

Reputation: 18526

Use a type guard:

const isFulfilled = <T,>(p:PromiseSettledResult<T>): p is PromiseFulfilledResult<T> => p.status === 'fulfilled';
const isRejected = <T,>(p:PromiseSettledResult<T>): p is PromiseRejectedResult => p.status === 'rejected';

const results = await Promise.allSettled(...);
const fulfilledValues = results.filter(isFulfilled).map(p => p.value);
const rejectedReasons = results.filter(isRejected).map(p => p.reason);

Upvotes: 29

vesse
vesse

Reputation: 5078

Like bela53 stated, use type guards. A more elegant solution than to inline the type guards is to define them as separate functions, and with generics binding you'd get the correct value too for the fulfilled promises, and can reuse for any allSettled filtering needs.

Casting is not needed (and generally should be avoided).

const isRejected = (input: PromiseSettledResult<unknown>): input is PromiseRejectedResult => 
  input.status === 'rejected'

const isFulfilled = <T>(input: PromiseSettledResult<T>): input is PromiseFulfilledResult<T> => 
  input.status === 'fulfilled'

const myPromise = async () => Promise.resolve("hello world");

const data = await Promise.allSettled([myPromise()]);

const response = data.find(isFulfilled)?.value
const error = data.find(isRejected)?.reason

Upvotes: 52

Yorgos Kakavas
Yorgos Kakavas

Reputation: 31

A bit more context for handling arrays:

const fulfilled = (res.filter((r) => r.status === 'fulfilled') as PromiseFulfilledResult<any>[]).map(
  (r) => r.value
);
(res.filter((r) => r.status === 'rejected') as PromiseRejectedResult[]).forEach((r) =>
  console.warn(r.status, r.reason)
);

Upvotes: 1

xyh
xyh

Reputation: 103

This makes ts not angry.

const rawResponse = await Promise.allSettled(promiseArray);
const response = rawResponse.filter((res) => res.status === 'fulfilled') as PromiseFulfilledResult<any>[];

const result = response[0].value

Upvotes: 2

Jens
Jens

Reputation: 470

Like Bergi mentioned TypeScript does not know if the type is PromiseFulfilledResult / PromiseRejectedResult when checking types.

The only way is to cast the promise result. This can be done because you already verified that the resolved promise is either fulfilled or rejected.

See this example:

const myPromise = async (): Promise<string> => {
  return new Promise((resolve) => {
    resolve("hello world");
  });
};

const data = await Promise.allSettled([myPromise()]);

const response = (data.find(
  (res) => res.status === "fulfilled"
) as PromiseFulfilledResult<string> | undefined)?.value;

if (!response) {
  const error = (data.find(
    (res) => res.status === "rejected"
  ) as PromiseRejectedResult | undefined)?.reason;
  throw new Error(error);
}

Upvotes: 24

bela53
bela53

Reputation: 3485

Define the find callback as type guard, that returns a type predicate:

type IMyPromiseResult = string

const response = data.find(
  (res): res is PromiseFulfilledResult<string> => res.status === 'fulfilled'
)?.value;

if (!response) {
  const error = data.find(
    (res): res is PromiseRejectedResult => res.status === 'rejected'
  )?.reason;
  throw new Error(error);
}

Demo Playground

Upvotes: 5

Related Questions