Last Updated: February 25, 2016
·
2.13K
· magalhini

Using $promises efficiently in $ajax

jQuery deferreds and promises have been around for quite some time now, but it's still very common to find projects where they could very well be used to make the code a bit tidier.

Let's say we want a pretty way to make requests to an API.
You'd simply want to call something like:

myApp.searchFor('grumpy cat');

... and immediately have the results returned, or to be able to easily attach multiple callbacks to this without making a mess out of your code.

Using the module pattern, we can make the requests in a very tidy and semantic manner.

var app = {

    // Base URL, if there's any
    getUrl: function (string) {
        return 'http://url-to-api/search/' + string;
    },

    // Build an object of requests.
    // Here's one for a search, which
    // takes only a query value.

    buildRequests: function () {
        this._api = {
            search: function (query) {
                // Creating a deferred
                var deff = $.Deferred();

                $.ajax({
                    url:     this.getUrl(query),
                    success: deff.resolve,
                    fail:    deff.reject
                });

                // We'll work with the outcome
                // of this promise!
                return deff.promise();
            }.bind(this)
        };
    }

    // We perform the search request,
    // and check the state of the request.
    // We can attach multiple callbacks.

    searchRequest: function (query) {
        this._api.search(query)
                 .done(function (data) {
                    console.log('Got data!');
                    return data;
                 })
                 .done(function (data) {
                    console.log('We can attach another callback');
                 })
                 .fail(function (data) {
                    console.log('Failure');
                 })
    }
};

// And we use it like this:
app.buildRequests();
app.searchRequest('cute kittens');

Note that you can attach multiple callbacks to your returned promises.
You can listen for done(), fail(), and then(); this last one will always run, even if the request has failed.

You can learn more about deferreds, including the very useful pipe() method, here: http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/

Have a fresh tip? Share with Coderwall community!

Post
Post a tip