Friday, August 16, 2013

JavaScript Promises

JavaScript Promises: by Shawn Wildermuth

A promise is a pattern for handling asynchronous operations. The problem is that essentially when you start an asynchronous operation, you need to execute some code as the operation is completed. Asynchronous code is so common that most libraries have found a solution for passing in callbacks. But there is little commonality to how each libraries does this...

a promise (is a) object that several JavaScript libraries use 
(including AngularJS, jQuery, Dojo and WinJS). 

The asynchronous operation simply returns an object called a promise.
The promise allows you to call a method called "then()" that let's you specify the function(s) to use as the callbacks.

then() function can accept two functions. The first is for the success callback; the second for the failure callback:

var $info = $("#info");

$.ajax({
    // Change URL to see error happen
    url: "/echo/json/",
    data: {
        json: JSON.stringify({
            "name": "someValue"
        })
    },
    type: "POST"
})
.then(function (response) {
    // success
    $info.text(response.name);
}, 
function () {
    // failure
    $info.text("bad things happen to good developers");
})
.always(function () {
    $info.append("...finally");
});

No comments: