XHR Promise Example

by Joshua McNeese

JavaScript

// a promise-wrapper around XHR
function request(method, url, args) {
    // Creating a promise and return it
    return new Promise(function (fulfill, reject) {
        // Instantiates the XMLHttpRequest
        var client = new XMLHttpRequest(),
            data;
        if (args) {
            if (method === 'POST' || method === 'PUT') {
                data = JSON.stringify(args);
            } else {
                url += '?';
                var argcount = 0;
                for (var key in args) {
                    if (args.hasOwnProperty(key)) {
                        if (argcount++) {
                            url += '&';
                        }
                        url += encodeURIComponent(key) + '=' + encodeURIComponent(args[key]);
                    }
                }
            }
        }
        client.open(method, url);
        if (data) {
            client.setRequestHeader('Content-Type', 'application/json');
        }
        client.send(data);
        client.onload = function () {
            if (this.status == 200) {
                // Performs the function "fulfill" when this.status is equal to 200
                fulfill(this.response);
            } else {
                // Performs the function "reject" when this.status is different than 200
                reject(new Error(this.statusText || 'Could not load'));
            }
        };
        client.onerror = function () {
            reject(new Error(this.statusText || 'Could not load'));
        };
    });

}

var url = 'https://developer.mozilla.org/en-US/search.json';
var args = {
    'q': 'Promise'
};

// Executes the XHR call 
request('GET', url, args)
    // parse the response string as JSON
    .then(JSON.parse)
    // log the JSON
    .then(function (data) {
        console.log('success', data);
    })
    // something threw an error!
    .catch(function (err) {
        console.log('failure', err);
    });