Basic Q promise

by kbcb

HTML

<script src="http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.6/q.js"></script>

JavaScript

function MyAsyncCall() {
    // Get a deferred object from Q library
    var deferred = Q.defer();
    
    // Do some asynchronous work
    $.ajax('http://cdnjs.cloudflare.com/ajax/libs/q.js/0.9.6/q.js')
        .success(function(data, textStatus, jqXHR) {
            // complete the promise (resolve) with the data you want in the .then() callback
            deferred.resolve(data.length);
        })
        .error(function(err) {
            // reject the promise with the error
            deferred.reject(err);
        });
    
    // Return the promise directly from the method
    return deferred.promise;
}

MyAsyncCall()
    .then(function(successData) {
        // promise has successfully completed
        alert('Success: ' + successData);
    })
    .catch(function(err) {
        // promise has completed with error
        alert('Error: ' + err);
    });