How to Promisify an Ajax Call

How to Promisify an Ajax Call

Tania Rascia  /  Leave a response

Let’s say you have an AJAX call, and some other function that depends on the AJAX call loading before it runs.

Here’s the AJAX function.

function doTheThing() {
    $.ajax({
        url: window.location.href,
        type: 'POST',
        data: {
            key: 'value'
        },
        success: function(data) {
            console.log(data);
        },
        error: function(error) {
            console.log(error);
        }
    });
}

And you might call the two functions in succession, and find that the second function doesn’t work, because it depends on the first one.

doThething();
doSomethingElse();

We can quickly and easily rewrite this with a Promise

function doTheThing() {
    return new Promise((resolve, reject) => {
        $.ajax({
            url: window.location.href,
            type: 'POST',
            data: {
                key: 'value'
            },
            success: function(data) {
                resolve(data);
            },
            error: function(error) {
                reject(error);
            }
        });
    });
}

Now we can do the AJAX call, run the success function, and follow it up with any subsequent code.

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

And that’s it!

Quality and morality on the web

Hi, my name is Tania Rascia. I've turned down every advertiser, sponsored post, and affiliate who has come to me. I give away all my knowledge for free to 300,000+ monthly readers and helped thousands of people learn and successfully transition into a design/development career.

You know what I stand for, and you know my commitment to you - no bullshit, no sponsored posts, no pop ups, no blocked content, ads, schemes, tactics, or gimmicks. Just free, quality content. If you enjoy my content, please consider supporting what I do!

Write a response

Your email address will not be published.

All code will be displayed literally.