关于$.when(...).then(...).finally is not a function报错的技术咨询
$.when(...).finally is not a function Error & Implementing Form Reset Got it, let's break down what's happening here and fix this issue step by step.
Why the Error Happens
The error you're seeing occurs because jQuery's Deferred object (the one returned by $.when()) doesn't have a finally() method. That method is part of the ES6 native Promise API, but jQuery uses its own Deferred interface—instead, jQuery provides the always() method which does exactly the same thing: it runs your callback regardless of whether the AJAX requests succeeded or failed.
Solution 1: Use jQuery's always() (Simplest & Most Compatible)
This is the quickest fix, since you don't need to change much of your existing code. Replace finally() with always():
$.when($.ajax("/page1.php"), $.ajax("/page2.php")) .then(function () { swal('success'); }) .always(function () { // Reset your form elements here—example: $('#your-form-id')[0].reset(); // Or manually clear fields if reset() doesn't work for your case: // $('#your-form-id input').val(''); // $('#your-form-id select').prop('selectedIndex', 0); });
Key Notes:
always()triggers after both AJAX requests complete, no matter if one (or both) failed. This perfectly matches your requirement to reset the form once the requests finish.- This works with all modern and older jQuery versions, so you don't have to worry about version compatibility.
Solution 2: Use Native Promise.all() (If You Prefer finally())
If you really want to use finally(), you can switch to native JavaScript's Promise.all() instead of $.when(). jQuery's $.ajax() returns a thenable object that works with native Promises (especially in jQuery 3.0+):
Promise.all([ $.ajax("/page1.php"), $.ajax("/page2.php") ]) .then(function () { swal('success'); }) .finally(function () { // Reset your form here $('#your-form-id')[0].reset(); });
Note:
- If you're using a very old jQuery version (pre-3.0), you might need to wrap each
$.ajax()call withPromise.resolve()to ensure it's a proper native Promise:Promise.all([ Promise.resolve($.ajax("/page1.php")), Promise.resolve($.ajax("/page2.php")) ]) // ... rest of the code stays the same
Which Should You Choose?
Stick with Solution 1 (always()) unless you have a specific reason to use native Promises. It's more aligned with jQuery's API and avoids any potential compatibility hiccups with older jQuery versions.
内容的提问来源于stack exchange,提问作者Jai Kumaresh

