XHR Promise Example

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.responseType,
            data;
        
        client.open(method, url);
        if (data) {
            client.setRequestHeader('Content-Type', 'application/xml');
            client.setRequestHeader('mode', 'no-cors');
            client.withCredentials = true;
            client.setRequestHeader('Access-Control-Allow-Origin', 'http://jsfiddle.net/lela2416/d4w8n8f8/');
        }
        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://transparency.entsoe.eu/api?securityToken=c1a81228-a8bb-465a-8a9e-e750a5634a71&documentType=A65&processType=A16&outBiddingZone_Domain=10YCZ-CEPS-----N&periodStart=201512312300&periodEnd=201612312300';
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);
    });