0

I've got a simple JQuery event handler that is triggered when a form is submitted.

$('.selector').on('submit', function(e) {
    e.preventDefault();

    submitForm(status).then(updateData());
});

I'm trying to add the capability to cancel the second call if the first one meets a certain condition but I can't get it working. I found this question but for some reason the second function still executes when reject() is returned. Rejecting A jQuery Promise In A $.ajax Success Method.

function submitForm(status) {
    return $.ajax({
        method: "POST",
        url: "/url/to/use",
        data: formData,
        dataType: "json",
        contentType: false,
        processData: false
    }).then(function(data) {
        if (data.error === true) {
            return new $.Deferred().reject().promise();
        } else {
            // do other stuff
        }
    });
}

Do I need to create a deferred object and return it or is that done by just calling then()? I've read quite a bit about deferred and promises but still can't understand how they work.

EternalHour
  • 8,308
  • 6
  • 38
  • 57
  • What version of jQuery are you running? jQuery 3.x behaves somewhat differently than 1.x/2.x. – jfriend00 Jul 03 '17 at 05:15
  • 1
    Uh, `submitForm(status).then(updateData());` should be `submitForm(status).then(updateData);`. Your first one ALWAYS calls `updateData()` and passes the return result as the `.then()` handler even before the promise calls the `.then()` handler. – jfriend00 Jul 03 '17 at 05:16
  • It's JQuery 1.12.4. – EternalHour Jul 03 '17 at 05:22

1 Answers1

0

Do I need to create a deferred object and return it or is that done by just calling then()? I've read quite a bit about deferred and promises but still can't understand how they work.

This is a problem with jQuery < 3 promises. In jQuery 3 the chaining issue was resolved and you can throw to signal an error.

Your code does not actually call updateData after the form is submitted as mentioned, you need to pass it a function and you're passing it a promise. A better promise library (like bluebird) or a type checker (like TypeScript) would have told you that :)

submitForm(status).then(updateData); // pass the function, don't invoke
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • It was calling `updateData`, the problem was I couldn't interrupt it when needed. I've changed it as you recommended but now it's not called at all. – EternalHour Jul 04 '17 at 01:04
  • Thanks for the recommendation but I decided to get rid of `then` and just call `updateData` inside the success callback. – EternalHour Jul 04 '17 at 03:28