Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  28] [ 2]  / answers: 1 / hits: 29292  / 4 Years ago, fri, november 20, 2020, 12:00:00

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?


More From » node.js

 Answers
26

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

[#50529] Wednesday, November 11, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lexusg

Total Points: 718
Total Questions: 106
Total Answers: 104

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
;