Code Pumpkin

Callbacks and Promises | Javascript

June 29, 2017
Posted by Pumpkin
Subscribe

In this article we will discuss about callback functions and promise in javascript. Callbacks and Promises are very important concepts of javascript as it helps it to support and leverage its asynchronous behaviour. First we explore on callback function and then promises.

Callbacks:

Let's first define the callback function: Callback function is any function that is called by another function. It passed as an argument to another function and is invoked after completion of certain event.

To understand it more clearly lest check the below example where we want to trigger a server response and display the response from the server.



request = prepareTheRequest()

response = sendRequestSynchronously(request)

display(response)

//now we can continue doing the other, totally unrelated things our program does
/* 
* some other code here 
*/

The above code work properly, but as we made it synchronous it will wait to complete the task at hand before moving to next instruction. Now if the server is slow, the user need to wait very long. Now lets write the same code in asynchronous way.



request = prepareTheRequest()

response = sendRequestSynchronously(request, function(response){
    display(response)    
})

//now we can continue doing the other, totally unrelated things our program does
/* 
* some other code here 
*/

Here while we wait for the response from server, we can move ahead to do execute other stuff that don't have to anything with the server response.

Our improved code is using callback function. As seen in previous example, to avoid blocking of execution when we waiting for some response from outer world, callbacks come to the savage. Below is also one similar example of callback function.


//We open the file and then write something to the file.

fileObj = open(file, function(fileObj){

    fileObj.write("Write something to the file.") 
})

/* 
* some other code here 
*/

Now here, when we are waiting file to open which is not in out hand, we can simply move further and execute other non related code. Once the file is opened the event will be triggered for the callback function and we will write to the file.

Promises:

When callbacks are really helpful in handling asynchronous code in javascript. It becomes messy when to many callbacks are nested and even it is difficult to handle errors.  When callbacks are the standard way of handling asynchronous code in javascript, promises are the best way to handle asynchronous code. 

Promises helps handle errors in asynchronous code and helps to write cleaner code by not having a callback functions.

A promise represents result of an asynchronous operation and it holds three states:

    pending: When promise it created it will be in the pending state. This state is mutable state of promise.

    fulfilled: Once the asynchronous request completed successfully without any error the state of promise change to fulfilled. This state of promise is immutable.

    rejected: If the asynchronous request completed with any error the state of promise change to fulfilled. This state of promise is immutable.

We use new Promise to construct the promise, the constructor is called immediately with two arguments – one that fulfils the promise and the other that rejects the promise. Promises wrap an asynchronous action in an object, which can be passed around and told to do certain things when the action finishes or fails.

The basic example of promise is as follow:


function get(url){

    return new Promise(function(sucess, fail){

        var req = new XMLHttpRequest();
        req.open("GET", url, true);
        req.addEventListener("load", function(){

            if(req.status == 200){
                succeed(req.responseText);
            }else{
                fail(new Error("Request failed: " + req.statusText));
            }

        });

        req.addEventListener("error", function(){
            fail(new Error("Network error"));
        });

        req.send(null);
    });

    })

}

get("exampleUrl/test.txt").then(function(text){
    console.log("test.txt: " + text);
}, function(error){
    console.log('Failed to fetch data.txt: " + error);
});

In the above example, The get function above receives a url, and returns a promise. The promise has a .then method which can be called with two functions, one to handle success, and the other to handle failure. 

That is all for callbacks and promises now.

Happy Learning 🙂

Tags: , ,


Comments and Queries

If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
<pre><code class="java"> 
String foo = "bar";
</code></pre>
For more information on supported HTML tags in disqus comment, click here.

Total Post : 80
Subscribe
Contribute Your Articles

Interview Experiences

Related Books

Like Us On Facebook

Alexa Page Rank