Native JavaScript Promises

Promises are awesome and the new native promise JavaScript implementation is great and pretty much entirely supported across all modern browsers. In the past developers used various different libraries like jQuery.Deferred() or Q to handle their promise implementations. However, with the native Promise object now in JavaScript in most if not all environments, these are no longer really needed. They’ll still work fine, but it would be advisable to start moving towards the native implementations of promises.

Below are 2 different examples of how you could use the native Promise object in JavaScript…

//2 different examples of promise usage.  
jQuery(document).ready(function() {  
    
    var test = [];

    function getPost(id){
        var def = new Promise(function(resolve, reject){
            jQuery.ajax({ 
                url: "http://jsonplaceholder.typicode.com/posts/" + id,
                type: "GET",
                dataType: "json",
                success: function(data){
                    test.push(data);
                    resolve(data)
                },
                error: function(){
                    reject();
                }
            }); 

        });

        return def;
    }

    // Implementation #1
    getPost(1).then(function(data){
        console.log(data);
        return getPost(2); 

    }).then(function(data){
        console.log(data);
        return getPost(3); 

    }).then(function(data){
        console.log(data);

    }).catch(function(error){
        console.log('Sorry an error ocurred!');
        def.reject();
    });   

});

Note that here I am only using jQuery’s AJAX method to do the asynchronous call to the demo API I am using that will give you back some sample JSON. You could just as easily do the above with the native XHR or even newer approaches such as fetch. As you probably already know, jQuery is an abstraction of native methods, so it makes sense that it ultimately does not matter what you use in our simple demonstration.

In the preceding example we looked at how you could implement the native Promise object if you needed a specific sequential order of the promises being returned. If you did not care at all about the order in which they came back and just needed to know when they *all* were finished you could do something like the below…

jQuery(document).ready(function() {  
    
    var test = [];

    function getPost(id){
        var def = new Promise(function(resolve, reject){
            jQuery.ajax({ 
                url: "http://jsonplaceholder.typicode.com/posts/" + id,
                type: "GET",
                dataType: "json",
                success: function(data){
                    test.push(data);
                    resolve(data)
                },
                error: function(){
                    reject();
                }
            }); 

        });

        return def;
    }

    // Implementation #2
    var arr = [getPost(1), getPost(2), getPost(3)]
    Promise.all(arr).then(function(values){
        console.log(values);
    });

});

Good stuff!

9bit Studios E-Books

Like this post? How about a share?

Stay Updated with the 9bit Studios Newsletter

0 Responses to Native JavaScript Promises

Leave a Reply