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!

Newsletter

Get updated when I create new content.
Unsubscribe whenever. Never any spam.

Note

I'm Tania. I turn down every ad, affiliate, and sponsor request I get. I write free resources that help thousands of people successfully become devs. If you enjoy my content, please consider supporting what I do.

Support my work

Write a response

Your email address will not be published. Required fields are marked *

All code will be displayed literally.

Discussion