Tania Rascia

Skip Navigation
How to Promisify an Ajax Call

How to Promisify an Ajax Call

 /  3 responses

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!

Note

Hi, my name is Tania Rascia. I've turned down every offer for advertisements or sponsored posts on this website. I write free resources that have helped thousands of people successfully transition into a web development career.

My committment is to no bullshit, no sponsored posts, no ads, and no paywalls. If you enjoy my content, please consider supporting what I do.

Support my work

Newsletter

New articles on web development every two weeks.

Write a response

Your email address will not be published.

All code will be displayed literally.

Discussion