Promises in JavaScript

ยท

2 min read

Well, we already know what a promise is. Unfortunately, we also know the feeling when someone breaks a promise ๐Ÿ˜ž. Thank God, computers are emotionless.

Let's try to think Algorithmically. When a promise is made to do something. One of the three outcomes is possible.

  • Work hasn't started yet. -- Pending

  • Work Finished --------> Successfully -- Fulfilled

  • Work Finished ---------> Unsuccessfully -- Rejected

Most of the work done in the Backend of a website is asynchronous. That simply means that, that work is not stopping other tasks from operating until it's completely over.

For example, if you are downloading something on your computer and someone messages you, you don't wait for the downloading to be over before you reply to the message.

Promises in JavaScript help us in achieving that Asynchronous procedure along with other funtions like Async(), Await() etc. Let's learn more about Promises, starting off with the syntax.


// syntax of Promise in JavaScript

// Declaration  
const promiseExample = new Promise((resolve, reject) => {
  resolve('success') //returns 'success' 
  reject('failure')  //returns 'failure'
})

//Calling the promise
// After promise is Finished , not necessarily Fulfilled
promiseExample.then(RESULT=>{"Things to do with RESULT if 
promise is Fulfilled"}).catch(ERROR =>{"Things to do with ERROR if 
promise is Rejected"})

In the above example, we can clearly see two arguments in our somewhat a callback function, resolve and reject. These two functions return the object that is supposed to be returned if the Promise is successfully resolved or rejected respectively. In our case, the resolve function is returning 'success' string and reject is returning 'failure' string.

Now, these returned objects are received by .then and .catch methods.


Let's write a Promise to generate a random single-digit number and assume that our promise would be Fulfilled if the randomly generated number is even. If that's the case, print the number on console, otherwise console.log('We are sorry but the generated number is odd').

const evenPromise = new Promise((resolve,reject)=>{
                // rNo is the random number.
            const rNo=Math.floor(Math.random()*9)
     if(rNo%2==0)
            resolve(rNo)
    else
            reject('We are sorry but the generated number is odd') })

// Let's call our Promise and see what we get .
evenPromise.then(result=>console.log(result)).catch(error=>console.log(error))

I hope this blog helped you understand Promises in JavaScript.

Let me know if I can improve somewhere. Thanks for reading it this far. Really means a lot to me.

ย