JavaScript Promises

As we discussed callback is in the callback function section and a lot of time it is very useful in our daily life programming but when we scale our project a lot of callbacks can create readability issues in our code. So that time we can use the concept of promise in our programming.

In javascript, a call executes in sequence like –


console.log("First"); 
console.log("Second"); 
console.log("Third");

// First, Second, Third

But sometimes we have some situation wherein our code sequence we need to wait for results. Like –


console.log("First");  
setTimeout(function() { console.log("Second"); }, 2000);
console.log("Third");

// First, Third, Second

Here the second line executes after 2 seconds and it is fine but what else if we need output like the first case? This means When you got the output of the second line of code then you need to execute the third line of code. If you have some pi and after you got the pi result then you need to execute the next line of code. You can write code like –


console.log("First");  
setTimeout(function() { 
    console.log("Second"); 
    console.log("Third");
}, 2000);

// First, Second, Third

Now you have achieved the same result but when you write a lot of code like this kind then you lose the readability of the code. So we have some elegant ways like Promise. We have promised syntax something like this –
promise


// Promise syntax
var promise = new Promise(function(resolve, reject) {
  // code 
});

Now we will solve the above problem in the promised way –


console.log("First");
var promise = new Promise(function(resolve, reject) {
    setTimeout(function() {  resolve(“Second”); }, 2000);
});

promise.then(function(res) {
    console.log(res);
    console.log("Third");
});

// First, Second, Third

Now you can see in Figure promise have 3 state –

pending Initial state neither successful nor failed
fulfilled operation successful
rejected operation failed

var promise = new Promise(function(resolve, reject) {
    var x = -2;
    
    if (x < 0) {
        reject("Negative numbers are not allowed.");
    } else {
        resolve("Successful")
    }
});
 
promise.then(
    function(result) { console.log(result) },  
    function(error) { console.log(error) } 
);

// We can also use this code

promise
.then(function(result) { console.log(result) })
.catch(function(error) { console.log(error) })

// Negative numbers are not allowed.

Now we can see; In this example where if the value of x is negative than in our code, an error block will run. If the value of x is positive then the success block will run.

We can also use finally in our code that will execute when our promise is settled means that it either resolves or reject. Like –


promise
.then(function(result) { console.log(result) })
.finally(function() { console.log("Promise is ready.”) })
.catch(function(error) { console.log(error) })

// Promise is ready
// Negative numbers are not allowed.

Key point – resolve and reject can use only once; we can’t use resolve or reject more than one time. Like


var promise = new Promise(function(resolve, reject) {
    resolve(“1”);
    setTimeout(function () {
 resolve(“2”); }, 1000);
});

promise.then(function(res) {
    console.log(res);
})

When we should use promise –
1. When we need to wait for time.
2. When we need to wait to upload a file, the image

Promises chaining

When we are using promise then we can also use a changing concept. Like –


new Promise(function(resolve, reject) {
    resolve("Good morning");
}).then(function(res) {
    var msg = "Mr. X, " + res;
    console.log("1: ", msg);
        
    return msg;
 }).then(function(res) {
    console.log("2: ", res, "!!!");
 })

// 1: Mr X, Good morning
// 2: Mr X, Good morning !!!

Now we can see the output of the first then can be used for a second then and so on.

About the Author: Pankaj Bisht