Promises Chaining vs Callback Pyramids


Chaining Promises vs Continuation Passing Style(CPS)


Lets see how Promises compare with CPS when trying to chain asynchronous operations.

Chaining Asynchronous Operations using the Continuation Passing Style:

getRandomNumber(function(number)){
    console.log(number); //logs 42

    getNameFromNumber(number, function(name)){
        console.log(name) //logs 'Bob'

        getAgefromNumber(age, function(age)){
            console.log(age) //logs 21
            //do something with age

        },
        function(error){
            console.log(error);

        }
    }, 
    function(error){
        console.log(error);

    }
},function(error){
    console.log(error);

});


Chaining Asynchronous Operations using Promises:


//getRandomNumber() returns a promise containing a random number
getRandomNumber().then(result => {  
    console.log(result) // 42
    return getNameFromNumber(result); //returns a promise containing a string representing a name

}).then(result2 => {
    console.log(result2) //"Bob"
    return getAgeFromName(result2);  //returns a promise containing a number representing an age

}).then(result3 => {
    console.log(result3) //21

}.catch(error => {
    console.log(error)
});

As you can see, it is difficult to make changes to a chain of asynchronous operations using CPS, especially since there has to be a callback for both the success and failure cases for each asynchronous call.

Promises allow asynchronous operations to be chained in a much more maintainable way.

results matching ""

    No results matching ""