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.
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__/*"]
}
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With