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:
- It takes an array of promises
- It waits for all promises to resolve
- Then it returns the result as an array
- If any one promise fails, it goes to
catch
userLogin()resolves after 3 secondsuserToken()rejects after 5 seconds- So, the result goes into the
catchblock
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:
- The promise which resolves first will give the result
- 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:
- Returns all results
- Shows status for each promise:
- fulfilled
- 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:
- If promise is resolved → goes to
then - If promise is rejected → goes to
catch