Promise – JavaScript

promise

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

In javascript, call execute 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. Means When you got the output of the second line of code then you need to execute the third line of code. Like you have some pi and after you got 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 of then we losing the readability of code. So we have some elegant way like Promise. We have promise syntax something like this –
promise


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

Now we will solve the above problem with promise 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, 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 either resolve 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 file, image

Promises chaining

When we are using promise than 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 first then can be used for a second then and so on.

You May Also Like

About the Author: Pankaj Bisht