What is promises in javascript ?
A promise is used to handle asynchronous operations in javascript .It has two outcomes resolve(success) or reject(failure) which are handled using .then() and .catch()
In other words we can say like this :- A promise in javascript is an object that represents the eventual completion or failure of an asynchronous operations and it's resulting value
Why we use Promises ?
Many callback become hard to read and hard to maintain it
it's an example of callback in the below code
getData1(function (r1) {
getData2(r1, function (r2) {
getData3(r2, function (r3) {
getData4(r3, function (r4) {
console.log(r4);
});
});
});
});
How to create a Promise ?
let p = new Promise((resolve, reject) => {
let success = true;
if (success) {
resolve("Promise Resolved");
} else {
reject("Promise Rejected");
}
});
Consuming a Promise
Now we have to use .then() and .catch() in the below examples
.then() runs when a promise is fulfilled
.catch() runs when a promise is rejected
Examples
p.then(result => {
console.log(result);
}).catch(error => {
console.log(error);
});
What is Promise Chaining ?
Using multiple .then() on a single promise is called Promise Chaining.
p
.then(result => result + " Step 1")
.then(result => result + " Step 2")
.then(result => console.log(result))
.catch(error => console.log(error));
What is Promise.all() ?
Used to execute multiple promises in parallel.
1.Multiple promise run together.
2.When all promises are being resolve .then() will run.
3.If one of the promise will reject than it will run .catch() piece of code
let p1 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("Promise 1 resolved")
},1000)
});
let p2 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("Promise 2 resolved")
},2000)
});
let p3 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("Promise 3 resolved")
},3000)
});
let p4 = new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve("Promise 4 resolved")
},4000)
});
Promise.all([p1,p2,p3,p4]).then((result)=>{
console.log(result);
}).catch((error)=>{
console.log(error);
})
Note:- If one of the promise is rejected then it will run in .catch() piece of code