Javascript: Returning data from an AJAX call

Javascript is by it's nature asynchronous, which makes returning data from an AJAX call complicated. Modern Javascript uses the concept of a "promise" to allow you to run code after an asynchronous call competes. This is similar to using a callback function, but it reads cleaner. JQuery implements this type of call with the then() function. A simple example is as follows:

function getData() {
    return $.ajax({
        url: '/api/data'
    });
}

// Usage
getData().then(function(data) {
    console.log(data);
});
Leave A Reply
All content licensed under the Creative Commons License