基于jQuery Deferred处理两Ajax请求一成功一失败的场景
Handling Mixed Success/Failure for Two jQuery Deferred Promises
Got it, let's break down how to handle the scenario where one of your Deferred promises (usedCarPurchaseInqPromise or hitRecoApi) succeeds and the other fails. Since you already have logic for when both succeed, here are two straightforward approaches to cover the mixed outcome case:
Approach 1: Track Individual Promise States
This method lets you explicitly track each request's success/failure status, then react once both requests have completed (regardless of outcome):
// Initialize flags to track each request's status let isPurchaseInqSuccess = false; let isRecoApiSuccess = false; // Handle first promise's success/failure usedCarPurchaseInqPromise .done(function(responseData) { isPurchaseInqSuccess = true; console.log('Used car purchase inquiry succeeded:', responseData); // Optional: Save response data for later use }) .fail(function(error) { isPurchaseInqSuccess = false; console.error('Used car purchase inquiry failed:', error); }); // Handle second promise's success/failure hitRecoApi .done(function(responseData) { isRecoApiSuccess = true; console.log('Recommendation API succeeded:', responseData); // Optional: Save response data for later use }) .fail(function(error) { isRecoApiSuccess = false; console.error('Recommendation API failed:', error); }); // React once both requests are done (success OR failure) $.when(usedCarPurchaseInqPromise, hitRecoApi) .always(function() { // Check for the "one success, one failure" scenario if ((isPurchaseInqSuccess && !isRecoApiSuccess) || (!isPurchaseInqSuccess && isRecoApiSuccess)) { console.log('One request succeeded, the other failed!'); // Branch logic based on which request succeeded if (isPurchaseInqSuccess) { // Logic for when purchase inquiry succeeded but recommendation API failed console.log('Proceeding with purchase inquiry data; ignoring recommendation failure'); // Add your custom handling here } else { // Logic for when recommendation API succeeded but purchase inquiry failed console.log('Proceeding with recommendation data; ignoring purchase inquiry failure'); // Add your custom handling here } } else if (isPurchaseInqSuccess && isRecoApiSuccess) { // Your existing "both succeeded" logic goes here console.log('Both requests succeeded!'); } else { // Optional: Handle case where both requests failed console.log('Both requests failed!'); } });
Approach 2: Use $.when() with State Checks
Since $.when() triggers its fail callback as soon as any promise rejects, you can check the state of the other promise inside that callback to determine the mixed outcome:
$.when(usedCarPurchaseInqPromise, hitRecoApi) .done(function(purchaseData, recoData) { // Your existing "both succeeded" logic console.log('Both requests succeeded:', purchaseData, recoData); }) .fail(function(error) { // At least one request failed—check the other promise's state if (usedCarPurchaseInqPromise.state() === 'resolved') { // Purchase inquiry succeeded, recommendation API failed usedCarPurchaseInqPromise.done(function(purchaseData) { console.log('Purchase inquiry succeeded, recommendation API failed:', purchaseData, error); // Add your custom handling here }); } else if (hitRecoApi.state() === 'resolved') { // Recommendation API succeeded, purchase inquiry failed hitRecoApi.done(function(recoData) { console.log('Recommendation API succeeded, purchase inquiry failed:', recoData, error); // Add your custom handling here }); } else { // Both requests failed console.log('Both requests failed:', error); } });
Key Notes:
- The
state()method returns'resolved','rejected', or'pending'—perfect for checking if a promise completed successfully even when$.when()hits a failure. - If your promises come from
$.ajax()calls, they’re already jQuery Deferred objects, so these methods work out of the box.
内容的提问来源于stack exchange,提问作者kumarmo2
相关产品推荐
相关产品推荐

