What are Promises in Javascript?

If an interviewer asks you "What do you understand by promises"? Then what will be your answer?

Here's the cleanest answer from the mdn documentation:

" A promise is basically an object which tells the eventual completion or failure of an asynchronous operation". Try breaking down this statement and understanding it.

Why there was a need for the Promises concept?

Earlier there were callback functions in javascript which were used to handle asynchronous operations. But often writing only 2 callback functions inside one another makes the code confusing to understand (also known as callback hell). Therefore to overcome this situation promises were introduced in javascript to handle asynchronous operations.

There are only 3 states possible in a promise:

pending: As the keyword suggests it is just an initial state.

fulfilled: As the keyword suggests it comes after the code has been successfully executed.

rejected: As the keyword suggests it comes after the operation is unsuccessful.

Syntax of declaring a Promise object

let promise_object = new Promise( function (resolve,reject){
//    Perform operations
});

In the above code, there is a Promise constructor which is taking a function as an argument. Now inside the function, two states are passed i.e., resolve & reject and therefore if the operations are performed completely & successfully then the resolve() function is called otherwise reject() is called.

Finally, let's take an example where we are calling resolve() function if the age of the person is greater than 18 otherwise we will call reject() function.

Code:

const age = 19;

let promise_object = new Promise(function (resolve, reject) {
    if (age>18) {
        resolve("The age of the person is above 18.");
    } else {
        reject("The age of the person is below 18.");
    }
});

console.log(promise_object);

Output:

Promise { 'The age of the person is above 18.' }

I hope you were able to grasp the basic concept of promises in javascript. In the next blog, we will be learning about Promise Chaining in-depth. Feel free to ask your doubts below or type your thoughts in the comment box.