Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Question 5 of 10 · Promises and Async/Await
Interview question

What is the difference between Promise.all(), Promise.race(), Promise.allSettled(), and Promise.any()? Promise.all(), Promise.race(), Promise.allSettled(), और Promise.any() में क्या अंतर है?

Answer
MethodResolves whenRejects when
Promise.all()All promises fulfillAny one rejects (fails fast)
Promise.race()First promise settles (fulfilled or rejected)First settled is a rejection
Promise.allSettled()All promises settle, regardless of outcomeNever rejects
Promise.any()First promise fulfillsAll promises reject
const p1 = Promise.resolve(1);
const p2 = new Promise(res => setTimeout(() => res(2), 100));
const p3 = Promise.reject('error');

// Promise.all - fails fast on first rejection
Promise.all([p1, p2])
    .then(results => console.log(results)); // [1, 2]
Promise.all([p1, p3])
    .catch(err => console.log('Failed:', err)); // Failed: error

// Promise.race - first to settle wins
Promise.race([p1, p2])
    .then(result => console.log('First:', result)); // First: 1

// Promise.allSettled - always resolves with status of each
Promise.allSettled([p1, p3]).then(results => {
    console.log(results);
    // [{status:'fulfilled', value:1}, {status:'rejected', reason:'error'}]
});

// Promise.any - first fulfillment, ignores rejections unless all fail
Promise.any([p3, p2])
    .then(result => console.log('First success:', result)); // First success: 2

// Practical use case - fetch data from multiple APIs concurrently
async function loadDashboard() {
    const [users, orders, stats] = await Promise.all([
        fetch('/api/users').then(r => r.json()),
        fetch('/api/orders').then(r => r.json()),
        fetch('/api/stats').then(r => r.json())
    ]);
    return { users, orders, stats };
}
Methodकब resolve होता हैकब reject होता है
Promise.all()सभी promises fulfill होंकोई एक reject हो
Promise.race()पहला promise settle होपहला settled reject हो
Promise.allSettled()सभी settle होंकभी reject नहीं होता
Promise.any()पहला fulfill होसभी reject हों
const p1 = Promise.resolve(1);
const p2 = new Promise(res => setTimeout(() => res(2), 100));
const p3 = Promise.reject('error');

// Promise.all - पहली rejection पर fail
Promise.all([p1, p2]).then(results => console.log(results)); // [1, 2]

// Promise.race - पहला settle जीतता है
Promise.race([p1, p2]).then(result => console.log('First:', result)); // 1

// Promise.allSettled
Promise.allSettled([p1, p3]).then(results => console.log(results));

// Promise.any
Promise.any([p3, p2]).then(result => console.log('Success:', result)); // 2

// Multiple APIs एक साथ
async function loadDashboard() {
    const [users, orders] = await Promise.all([
        fetch('/api/users').then(r => r.json()),
        fetch('/api/orders').then(r => r.json())
    ]);
    return { users, orders };
}

Was this answer clear?