What is a Promise🤞?
By the definition of MDN,
The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
We know that JavaScript is a synchronous programming language but callback function makes it Asynchronous.
Let's understand promise by simple example, suppose you made a promise🤞 to yourself that you will wake up at sharp 5AM. But eventually, you don't know whether you will make it or not, that means either you are going to complete that promise or not.
How it works?
The promises returns one of the 3 possible states:
- Fullfilled: You woke up at sharp 5AM.
- Rejected: You didn't wake up at 5AM.
- Pending: You don't know if you'll wake up or not.
A promise is settled if it's not pending means it has been resolved or rejected. After it has been settled there is no use of calling resolve()
or reject()
.
Syntax📃
new Promise( (resolve, reject)=> { ... } );
For example📃 ,
let wakePromise = true;
let wakeUp = new Promise((resolve, reject)=> {
setTimeout(() => {
if (wakePromise) {
resolve('I woke up');
}
else {
reject('I didnt wake up'); }
}, 5000);
});
console.log(wakeUp);
Output:
After completion of 5 seconds the promise gets fulfilled.
If we change wakePromise = false
then it returns,
So the reject method moved the promises to the rejected() state.
Static types and prototype method:
- Promise.prototype.then(onFulfilled, onRejected)
.then
method is used to schedule📅 a callback to be executed when the promise is successfully resolved.
- Promise.prototype.catch(onRejected)
.catch
method is used to schedule📅 a callback to be executed when the promise is rejected.
- Promise.prototype.finally(onFinally)
.finally
is used to execute the same piece of code whether the promise is fulfilled or rejected.
For example📃 ,
function makePromise(wakeUp) {
return new Promise(function (resolve, reject) {
setTimeout(() => {
if (wakeUp) {
resolve("I woke up at 5AM.");
} else {
reject("I didn't wake up at 5Am.");
}
}, 5 * 1000);
});
}
let wakeUp = makePromise(true);
wakeUp
.then(success => console.log(success))
.catch(reason => console.log(reason))
.finally(() => console.log("Let's sleep"));
Output:
Promise🤞 Chaining
Promise Chaining is a concept by which we may initialize another promise inside our .then() method and accordingly we may execute our results.
For example📃 ,
let promise = new Promise((resolve, reject) => {
resolve("Test");
});
promise
.then(
new Promise((resolve, reject) => {
resolve("exams");
})
.then((result1) => {
console.log(result1);
})
)
.then((result2) => {
console.log(result2);
});
Output:
We can use promise.all()
for the nested .then
method. It can simply the messy code easily. It rejects immediately upon any of the input promises rejecting or non-promises throwing an error, and will reject with this first rejection message / error.
For example📃 ,
const Promise1 = new Promise((resolve, reject)=>{
setTimeout(() => {
console.log('The first promise has resolved');
resolve(10);
}, 1 * 1000);
})
const Promise2 = new Promise((resolve, reject)=>{
setTimeout(() => {
console.log('The second promise has resolved');
resolve(10);
}, 1 * 1000);})
Promise.all([Promise1, Promise2])
.then((data)=>{
console.log(data);
})
.catch((error)=>{
console.log(error)
})
Important points
- Use promises whenever you are using async or blocking code.
- A promise is an object that returns a value in the future.
- A promise starts in the pending state and ends in either a fulfilled state or a rejected state.
-
resolve
maps tothen
andreject
maps tocatch
- If something needs to be done in both cases use
.finally
Thanks for reading my post. I hope you've liked it. Happy coding😊
Some more blogs by me💗
Some best techniques to Optimize your React App🐱💻
Top comments (0)