What is Promise?
Promise is an object that is used to handle asynchronous operation.
This will execute either resolve or reject
if resolve, it will execute then block
else, it will execute catch block
Why we use Promise?
1.Avoid Callback Hell
Promises allow you to chain asynchronous operations instead of nesting them. This is done using .then()
2.Error Handling
With callbacks, you had to check for errors at every single level of nesting. Promises provide a single .catch() method at the end of the chain.
so,it makes easy to check the error
When should we use Promise?
- When Making Network Requests
- When Working with Databases
- When Reading or Writing Files
- When Using Timers or Delays
Example
function booking(){
return new Promise((resolve,reject)=>{
let bookingsuccess=true;
if(bookingsuccess)
resolve(850)
else
reject()
})
}
booking().then(()=> console.log("booking success"))
.then((amt)=> console.log('i have transfered ${amt}'))
.catch(()=> console.log("try again"))
Top comments (0)