Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get the value from Promise.allSettled in NodeJs 12 with Typescript 3.8.3 version

I am learning NodeJs 12 with Promise.allSettled() function and its usage. I have written the following code. I am able to print the status in the console but unable to print the value as it is giving compilation issue.

        const p1 = Promise.resolve(50);
        const p2 = new Promise((resolve, reject) =>
            setTimeout(reject, 100, 'geek'));
        const prm = [p1, p2];

        Promise.allSettled(prm).
        then((results) => results.forEach((result) =>
            console.log(result.status,result.value)));

I am getting the following compilation issue. enter image description here

I provide below the tsconfig.json.

{
  "compilerOptions": {
    "target": "es2017",
    "lib": ["es6","esnext", "dom"],
    "allowJs": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "declaration": true,
    "outDir": "./lib",
    "strict": true,
    "esModuleInterop": true,
    "typeRoots": [ "./types", "./node_modules/@types"]
  },
  "include": ["src"],
  "exclude": ["**/__tests__/*"]
}
like image 489
Deba Avatar asked Jul 27 '20 16:07

Deba


People also ask

What happens if one promise fails in promise all?

In other words, if any promise fails to get executed, then Promise. all() method will return an error and it will not take into the account whether other promises are successfully fulfilled or not.

What is promise allSettled?

The Promise. allSettled() method returns a promise that fulfills after all of the given promises have either fulfilled or rejected, with an array of objects that each describes the outcome of each promise.

What is the difference between promise all and promise allSettled?

all() method returns an array as an output containing promise data inside several indexes. Promise. allSettled() method returns an array of objects and each of these objects further contains two properties further status and value.

How do I use promises in node JS?

A Promise in Node means an action which will either be completed or rejected. In case of completion, the promise is kept and otherwise, the promise is broken. So as the word suggests either the promise is kept or it is broken. And unlike callbacks, promises can be chained.


1 Answers

You might want something like this:

  Promise.allSettled(prm).
    then((results) => results.forEach(result => {
       if (result.status === 'fulfilled') {
         console.log(result.status,result.value);
       } else {
         console.log(result.status,result.reason);
       }
    });

value only exists if the status is fulfilled, but it doesn't cover cases where one of the promises had an error.

like image 112
Evert Avatar answered Sep 21 '22 01:09

Evert