Javascript – jQuery 3.1.0 then(), done() and when() error swallowing

javascriptjquery

Using jQuery 3.1.0, I am creating an unknown number of $.ajax() requests and adding the resulting promise(s) into an array using:

myArray.push($.ajax(...).promise());

Once all of the requests are completed I want to call a function, which I understand can be done using:

$.when.apply($, myArray).then(myFunction, errorHandlingFunction);

However, myFunction is throwing an error that is being swallowed by jQuery (during testing all my function did was call throw new Error()). I can see that execution enters the catch after calling mightThrow() and correctly reject's the deferred but this is never shown in the console.

Even doing the following, which omits the apply call, results in the error being swallowed completely; the debugger line is also never hit:

myArray[0].then(function() {
    throw new Error('test error');
}, function() { debugger; });

Removing the when() and performing the following causes execution to break on the throw:

myArray[0].done(() => {
    throw new Error('test error');
}).fail(function(){ debugger; });

It seems that errors that occur in the function executed by then() are always swallowed. In addition, $.when(...).done(...) also results in the error being swallowed if the function inside done() throws.

Have I misunderstood something or is this a bug/feature of jQuery?

Best Answer

You will need to use .then(myFunction).fail(myErrorHandling). Throwing the error within myFunction will reject the new promise created by then() which then can be handled in fail().

The error handling function in .then(myFunction, myErrorHandling) is called when the promise received by then() is rejected. This is only the case when at least one of your ajax requests from the $.when() fails.