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);
});


Note: Replies will be formatted with PHP Markdown Extra syntax.

Name: Email (Not Required):
 
Logged IP: 216.73.216.238
To prevent spam please submit by clicking the kitten: