Promises give you hope of your wishes being granted somewhere in the future. Everyone has been promised by someone at some point in their life, and that's a sure thing. The only problem is promises aren't always fulfilled.
We make promises when we claim to do something in the future and javascript promises are the same. Promises always result in fulfillment or rejection. Enough talk, lets begin coding.
let mommysPromise = new Promise((resolve, reject)=>{
setTimeout(()=>resolve("Buys a birthday present!"), 2000)
});
So you can see that my mom promised me to buy a car, there are two possibilities, either she keeps her promise resolve
or she doesnot keep the promise reject
. In javascript world she either resolves or rejects her promise, the result of
which i will only know when the time comes.
I will only know that mommy kept her promise is, if i remember that she made a promise in the first place. Otherwise,
there is a high chance that I wont remember the promise.
So what do we do in javascript world to keep an eye on the promise? We can do two things, either use async/await or
use a .then
chain.
mommysPromise.then(
data=>console.log(data),
error=>console.log(error)
)
As you can see the .then
takes two function as its argument. It will call the first function if promise
resolves,
otherwise it will call the second function passing in the error/reason for rejection.
Pl. Note - The writer has been a victim of broken promises. Join the squad now! 😜