1

I'm struggling with an ajax GET using a promise. If the ajax runs into an error, such as the URL is incorrect, the 'error: function ()' is called and I get an error in the browser debug saying "Uncaught (in promise) undefined"

The first two parts of the ajax function works OK i.e. if the ajax returns a success, then both inner conditions for result.success true/false are working, I just don't know how to resolve the reject call in the ajax error function at the bottom:

    var myVariable = "test";
    let promise = myFunction(myVariable);
    
    promise.then(function () {
        // Do Something           

    }).catch(function (message) {

        console.error(message);
    });     

    function myFunction(myVariable) {

    return new Promise(function (resolve, reject) {

        $.ajax({
            type: "GET", //send it through get method
            url: "/myURL/Edit?handler=GetBlahBlah",
            data: {
                sourceType: myVariable
            },
            contentType: "json",
            dataType: "json",
            success: function (result) {
                if (result.success == false) {
                    reject(result.responseText); // This works
                } else {
                    resolve(); // This works
                }
            },
            error: function () {
                reject("Error while making Ajax call! Get Trigger"); // NOT WORKING!!
            }
        });
    });
}
OJB1
  • 2,245
  • 5
  • 31
  • 63
  • Does this answer your question? [Rejecting A jQuery Promise In A $.ajax Success Method](https://stackoverflow.com/questions/36889451/rejecting-a-jquery-promise-in-a-ajax-success-method) – Zac Anger Jan 10 '21 at 22:50
  • No that doesn't help, don't understand their use case which looks different to my example. An explanation would help please. – OJB1 Jan 10 '21 at 22:52
  • They had the same problem: mixing promises and success/error functions on the ajax options object. You don't need to wrap .ajax in a promise, it already returns a promise. I'll add an answer with example code. – Zac Anger Jan 10 '21 at 22:56

1 Answers1

1

Turns out my original question does actually work correctly, I hadn't noticed at first that the calling method to this ajax GET request was coming from two different process in my javascript at different times and i hadn't included a catch block on the process that was actually calling this ajax the first time round. Apologies if I caused any confusion to anyone, my bad!

OJB1
  • 2,245
  • 5
  • 31
  • 63