JavaScript (JS) Bytes 5

JavaScript

As the name implies a JavaScript Promise object returns a clause telling that as of now the object is yet to be resolved, but once it is fulfilled , it will execute the next line of the script asynchronously

Initially promises weren't natively available in JavaScript till recently google made it available in Chrome, followed by other Browser's JS Engine.

At their most basic, promises are a bit like event listeners except:

  • A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.
  • If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.

This is extremely useful for async success/failure, because you're less interested in the exact time something became available, and more interested in reacting to the outcome.

A promise can be:

  • fulfilled - The action relating to the promise succeeded
  • rejected - The action relating to the promise failed
  • pending - Hasn't fulfilled or rejected yet
  • settled - Has fulfilled or rejected

Before digging into Promise, let's understand the context of where promises comes into picture in first place.

A lot of JavaScript developers write spaghetti / Christmas Tree code, i.e nesting callbacks one after the other. This results in Callback Storm. Let me explain this with a well illustrated example:

//Js Bytes 5
function asynMethod(message, cb) {
    setTimeout(function(){
        console.log(message);
        cb();
    }, 500);
};
//christmas Tree code
asynMethod('Open the tunnel', function(){
    asynMethod('Start the callback Storm', function(){
        asynMethod('Go deep into the storm', function(){
            asynMethod('Finally end it !', function(){})
        })
    })
})

Here you can see how the callbacks are nested one after the other resulting in a complete mess , however a principled JavaScript developer will never use this style of approach even when it works the same.

//Let's use promsises and avoid callback hell
function asyncMethod(message) {
    return new Promise(function(fulfill, reject) {
        setTimeout(function(){
            console.log(message);
            fulfill();
        },500);
    });
};

function findTunnel() {
    asyncMethod('Start the callback Storm').then(deepTunnel)
}
function deepTunnel(){
    asyncMethod('Go deep into the storm').then(stopStorm)
}
function stopStorm(){
    asyncMethod('Finally end it !').then(function(){})
}
asyncMethod('Open the tunnel').then(findTunnel)

Now compare how it looks better the code shown above:

Let's go one step further , as mentioned at first Promises are objects which are first class functions, hence we can further optimize them as shown, and make them thenable. 

//Going one step further on Promises ! 
//Returning Promises 
function findTunnel() {
    return asyncMethod('Start the callback Storm')
}
function deepTunnel(){
    return asyncMethod('Go deep into the storm')
}
function stopStorm(){
    return asyncMethod('Finally end it !')
}
asyncMethod('Open the tunnel')
    .then(findTunnel)
    .then(deepTunnel)
    .then(stopStorm)
    .then(function(){})

Thus the chain of then is constructed which is a common design pattern of Promises. Note: There are several ways of resolving and working with Promise , this is one among it.

Thank you sticking together so far. Let's bring the best of JS in the upcoming JavaScript Bytes from bludle.

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.