Dan Def Dan Def - 1 year ago 98
jQuery Question

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

Using jQuery 3.1.0, I am creating an unknown number of

requests and adding the resulting promise(s) into an array using:


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
). I can see that execution enters the catch after calling
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
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
are always swallowed. In addition,
also results in the error being swallowed if the function inside

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download