Issue
I've been trying to use Promise.allSettled on NodeJS with Typescript recently, and I'm facing issues with the response. the allSettled method returns an array with status: "rejected" | "fulfilled"
and a value, in case it's fulfilled. The problem is, when I try to access the value of the response, I get the following errors:
Property 'value' does not exist on type 'PromiseSettledResult<unknown>'.
Property 'value' does not exist on type 'PromiseRejectedResult'.ts(2339)
Below I'll leave a simple example so you can copy the code and try yourself:
const p1 = Promise.resolve(50);
const p2 = Promise.resolve(100);
const promiseArray = [p1, p2];
Promise.allSettled( promiseArray ).
then( results => results.forEach( result =>
console.log(result.status, result.value)));
If I run this code on my project, I get an error because of result.value
at the end.
I'm running my node on version 12.18.3 on Windows, and I've set my target on the tsconfig.json
as ES2020
to be able to use the method itself.
Solution
@jonrsharpe answered it: You only have a value attribute where the status is fulfilled, and you're not checking for that.
So using my own example, it can be fixed as the following:
const p1 = Promise.resolve(50);
const p2 = Promise.resolve(100);
const promiseArray = [p1, p2];
Promise.allSettled( promiseArray ).
then( results => results.forEach( result =>
console.log(result.status,
result.status === 'fulfilled' && result.value
);
));
It now verifies if the promise was fulfilled and then prints the value, if it's the case.
Answered By - Cassio Groh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.