Header Ads

JavaScript Promises

JavaScript Promises
To handle promises running concurrently you need to push them into an array. Then use the methods available in the next slides to handle differnt type of cases.
let requests;
requests.push(fetch("api.dev.com/users"));
requests.push(fetch("api.dev.com/repos"));
Promise.all() Waits for all the promisesto be resolved or any to be rejected.
Promise.all(requests)
   .then(resArray => {
   // do something with the responses
   })
   .catch(error => {
   // handle error
   })
Promise.allSettled() Wait until all promises have settled(each may resolve to reject)
Promise.allSettled(requests)
.then(resArray => {
// do something with the responses
   })
   .catch(error => {
   // handle error
   })
Promise.race() Wait untill any of the promise is resolved or rejected
Promise.race(requests)
.then(resArray => {
// do something with the responses
   })
   .catch(error => {
   // handle error
   })

No comments:

Powered by Blogger.