Q.js example

by Luis Valle

HTML

<script src="https://raw.githubusercontent.com/kriskowal/q/v1/q.js"></script>

JavaScript

function AJAXcall(aFunction, spParams) {
    if (!jQuery.support.cors) {
        jQuery.support.cors = true;
    }
    
    var d = $.Deferred();
    // https://www.evicore.net/webservices/evicoreservice.asmx/ + aFunction
    $.ajax({
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        url: '/echo/json/',
        data: JSON.stringify(spParams),
        type: "POST",
        dataType: "json"
    })
    .done(function (response) {
        d.resolve((response.hasOwnProperty('d') ? $.parseJSON(response.d) : spParams));
    })
    .fail(function (jqXHR, textStatus, errorThrown) {
        if ($.trim(errorThrown) == '') {
            /* If this webpage exists in the same Domain as the webService it will throw a weird blank error, so we ignore it */
            d.resolve({ 'error': '0' });
        } else {
            errorThrown = 'Ajax communication failed!\n\n(Error Thrown: "' + errorThrown + '")';
            d.resolve({ 'error': '1', 'errorCode': errorThrown });
        }
    });
    
    return d.promise();
}

$(document).ready(function () {
    Q(
        AJAXcall('', {hisAge: 0})
    )
    .then(function(n) {
        alert(JSON.stringify(n));
        return ++n.hisAge;
    })
    .then(function(n) {
        return ++n;
    })
    .then(function(n) {
        return ++n;
    })
    .then(function(n) {
        alert("done: " + n);
    });
});