WebTuts - seomat.com

Your ultimate destination for comprehensive, easy-to-follow web tutorials.

Promisify an Ajax call

Promisifying an Ajax call involves encapsulating it in a Promise to handle asynchronous operations more elegantly.

Suppose you have an AJAX call, along with another function that depends on the AJAX call being loaded before its execution.

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

Furthermore, you could potentially invoke the two functions consecutively and observe that the second function fails to operate due to its reliance on the first one.

doTheFirstThing();
doTheSecondThing();

We can rewrite this with a Promise:

function doTheFirstThing() {
    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 have the capability to execute the AJAX call, trigger the success function, and then proceed with any subsequent code.

doTheFirstThing()
.then((data) => {
    console.log(data);
    doTheSecondThing();
})
.catch((error) => {
    console.log(error);
});