Home Courses Promise.all - Promise.race and Promise.allSettled

Promise.all - Promise.race and Promise.allSettled

Promise.all()

Sometimes, you don’t have just one promise. You can have multiple promises, and you may want to resolve all of them together.

For that, we use Promise.all().

Example from the script:


function handleLogin(){
const loginPromise = userLogin();
const tokenPromise = userToken();

Promise.all([loginPromise, tokenPromise]).then((result)=>{
console.log(result);
}).catch((err)=>{
console.log(err);
})
}

How it works:

  1. It takes an array of promises
  2. It waits for all promises to resolve
  3. Then it returns the result as an array
  4. If any one promise fails, it goes to catch


  1. userLogin() resolves after 3 seconds
  2. userToken() rejects after 5 seconds
  3. So, the result goes into the catch block


Promise.race()

If you want the result of only the first resolved promise, you can use Promise.race().


Promise.race([loginPromise, tokenPromise]).then((result)=>{
console.log(result);
})

How it works:

  1. The promise which resolves first will give the result
  2. Other promises are ignored


Promise.allSettled()

If you want results of all promises, whether they succeed or fail, use Promise.allSettled().


Promise.allSettled([loginPromise, tokenPromise]).then((result)=>{
console.log(result);
})

How it works:

  1. Returns all results
  2. Shows status for each promise:
  3. fulfilled
  4. rejected


Error Handling with catch()

When a promise fails, we use catch() to handle the error.

Example:


Promise.all([loginPromise, tokenPromise]).then((result)=>{
console.log(result);
}).catch((err)=>{
console.log(err);
})

Or with a single promise:


loginPromise.then((result)=>{
console.log(result);
}).catch((err)=>{
console.log(err);
})

How it works:

  1. If promise is resolved → goes to then
  2. If promise is rejected → goes to catch


Share this lesson: