Promise.allSettled


function getUser() {
return fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json());
}
function getPost() {
return fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json());
}
function getComments(){
return fetch('https://jsonplaceholder.typicode.com/comments').then(res => res.json());
}
async function getAlldata() {
try{
const [ users, posts, comments ] = await Promise.allSettled(
[
getUser(),
getPost(),
getComments(),
]
)
console.log(JSON.stringify(users, null, 2));
console.log(JSON.stringify( posts, null, 2));
console.log(JSON.stringify(comments, null, 2));
}catch(err){
console.log(err);
}
}
getAlldata();

Promise.all

function getUser() {
return fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json());
}
function getPost() {
return fetch('https://jsonplaceholder.typicode.com/posts').then(res => res.json());
}
function getComments(){
return fetch('https://jsonplaceholder.typicode.com/comments').then(res => res.json());
}
async function getAlldata() {
try{
const [ users, posts, comments ] = await Promise.all(
[
getUser(),
getPost(),
getComments(),
]
)
console.log(JSON.stringify(users, null, 2));
console.log(JSON.stringify( posts, null, 2));
console.log(JSON.stringify(comments, null, 2));
}catch(err){
console.log(err);
}
}
getAlldata();

Promise.all([..]) vs Promise.allSettled([…])

Promise.all()

Waits for all promises to succeed.

If one promise rejects, the entire operation rejects immediately.

Promise.allSettled()

Waits for all promises to finish, whether they succeed or fail.

Promise.any([..])

Returns the first fulfilled (successful) promise.

First Success Wins

const p1 = Promise.reject("Server 1 failed");
const p2 = Promise.resolve("Server 2 success");
const p3 = Promise.resolve("Server 3 success");
const result = await Promise.any([p1, p2, p3]);
console.log(result);
Output:
Server 2 success

It ignores rejected promises unless all promises fail.

Promise.Race([…])

Whoever crosses the finish line first wins. Doesn’t matter whether they finished successfully or crashed. Promise.race() only cares about who settles first.

const promise1 = new Promise(resolve => setTimeout(() =>
resolve('Promise one reslove')
, 1000));
const promise2 = new Promise(resolve => setTimeout(() => resolve('Promise two reslove'), 2000));
async function getData(){
const res = await Promise.race([promise1, promise2]);
console.log(res);
}
getData();

Leave a comment

Quote of the week

"People ask me what I do in the winter when there's no baseball. I'll tell you what I do. I stare out the window and wait for spring."

~ Rogers Hornsby