Skip to main content

Example demonstrating how to Promisify an jQuery Ajax request.

/**
 * From "How to Promisify an Ajax Call" at https://www.taniarascia.com/how-to-promisify-an-ajax-call/
 */
function doTheThing() {
    return new Promise(function(resolve, reject) {
        $.ajax({
            url: window.location.href,
            type: "POST",
            data: {
                key: "value"
            },
            success: function(data) {
                resolve(data);
            },
            error: function(error) {
                reject(error);
            }
        });
    });
}

//
// Usage

doTheThing()
    .then(function(data) {
        console.log(data);
        doSomethingElse();
    })
    .catch(function(error) {
        console.log(error);
    });