Quantcast
Channel: JavaScript – 9bit Studios
Viewing all articles
Browse latest Browse all 32

Native JavaScript Promises

$
0
0

Promises are awesome and the new native promise JavaScript implementation is great and pretty much entirely across all modern browsers. In the past developers used various different promise libraries like jQuery.Deferred() or Q. However, with the native Promise now in JavaScript in most if not all environments, these are no longer really needed.

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

//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();
    });   

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


});

Good stuff!


Viewing all articles
Browse latest Browse all 32

Latest Images

Trending Articles





Latest Images