I Was Scared of JS Promises In 2017, But I’m Super-Brave in 2020 (Learn My Tricks)

It rained all day and my little sister was terribly bored. 

She said, Grand-dad, Please! Tell us a story about the olden days. Grandfather smiled and he began the story,

“Once long ago, when I was a boy, we had No money to pay for daily transport. So i used to Walk to college.

One day my father bought a lotto ticket and promised that he’ll get me a new cycle next week.”

Before my Grandpa could say next word, The doorbell rang…

Ting Tong !

I opened the door , He was my grandpa childhood friend, soon grandpa got busy talking to him.

We also went away to watch our favourite daily soap Shaktiman in our room.

I never got to know what happened next but the promise my great-grand father did had 3 states.

1 – Pending: My grandpa didn’t know if he will get that cycle.

2 – Fulfilled: He wins the lotto , and he buys my grandpa a brand new cycle.

3 – Rejected: He doesn’t wins the lotto, and he could not afford to buy a cycle.

Converting this to a JavaScript Promise:-

I’m a Big fan of official documentation so first, Please take a good look at MDN definition of Promise.

Promise is a proxy for a value not necessarily known when the promise is created. instead of immediately returning the final value, the asynchronous method returns a promise to supply the value at some point in the future.

const newcycle = (lotto) => {
return new Promise((resolve,reject) => {
        if(!lotto) {
            reject(`couldn't afford`) // reject
        } else {
            resolve(`${lotto} lottery got my grandpa brand new cycle`) 
          // fulfilled
        }
    })
}

// The code above was quite expressive in itself.

// consuming promise 

newcycle('5k ruppese').then((fullfilled) => {
    console.log(fullfilled); // yay, grandpa got a new cycle
})
.catch((err) => console.log(err));

// Expected Output = 5k ruppese lottery got my grandpa brand new cycle
Chaining Promises: –

Let’s Imagine grandpa had promised his college friend, that he will lift him on his Bi-cycle when his father buys him one.

Look at the promise chaining Example

const newcycle = (lotto) => {
return new Promise((resolve,reject) => {
        if(!lotto) {
            reject(`couldn't afford`)
        } else {
            resolve(`${lotto} lottery got my grandpa brand new cycle`)
        }
    })
}

const liftFriendOnCycle = () => {
  return new Promise((resolve,reject) => {
    resolve(`Hey friend i got a new cycle`);    
  })}

  newcycle('5k ruppese').then(liftFriendOnCycle)
               .then(fullfilled => {
                   console.log(fullfilled)
               } )
                
               .catch(err => console.log(err))

// Expected Output = Hey friend i got a new cycle

Bonus – Rewrite Promise chaining example with ES7 syntax

Async-Await:
const newcycle = (lotto) => {
return new Promise((resolve,reject) => {
        if(!lotto) {
            reject(`couldn't afford`)
        } else {
            resolve(`${lotto} lottery got my grandpa brand new cycle`)
        }
    })
}

const liftFriendOnCycle = () => {
  return new Promise((resolve,reject) => {
    resolve(`Hey friend i got a new cycle`);    
  })}

  async function ola() {
    try {
        let promise1 = await newcycle('5k')
        let promise2 = await liftFriendOnCycle();
        console.log(promise1)
        console.log(promise2);
    } catch (err){
        console.log(err);

    }
}

ola();

// Expected Output - 5k lottery got my grandpa brand new cycle 
// Expected Output - Hey friend i got a new cycle

Closing Notes– If you like codeum.io and would like to contribute, you can also write an article by sending a mail to me at contact@taniskjha.com or alternatively you can Dm me on Facebook or Twitter too.

See your article appearing on the codeum.io main page with over 10k Monthly Visitors and help other aspiring Developers.

Thanks for reading,If you have any questions , please ask questions in the comments below.

If this post was helpful, help me back by clicking the Share button.

More Posts:-

Step by Step plan that will Get You From ZERO to PASSING a coding interview (at Google, Facebook, Amazon)

Calling All New Developers. Understand How do JS closures work?

The Ultimate Guide to become a full stack web developer in 3 easy step

7 Amazing Array Methods to Boost your Javascript Skills Today

33 Most Powerful linux Commands To Run in Terminal

Who Else Wants to Clear confusion about Javascript Hoisting [Step-by-Step]

Tanisk jha

Mission-Driven Self taught Software Developer with a passion for thoughtful UI Design, collaboration and writing.
Tanisk jha

One thought on “I Was Scared of JS Promises In 2017, But I’m Super-Brave in 2020 (Learn My Tricks)

Leave a Reply

Your email address will not be published. Required fields are marked *