如何在jQuery 3.6中复用相同端点的AJAX请求代码?
复用jQuery AJAX请求及重试逻辑的方案
核心思路
把固定的AJAX配置、重试逻辑封装成通用函数,将不同业务场景下的成功/失败处理逻辑以回调参数传入,彻底消除重复代码。
基础实现:通用请求函数
以下是封装了请求配置和重试逻辑的通用函数:
function makeApiRequest(req, onSuccess, onError) { const baseUrl = "/api/url"; const timeout = 10000; const retryLimit = 1; function executeRequest(tryCount = 0) { $.ajax({ type: "POST", url: baseUrl, contentType: "application/json", data: JSON.stringify(req), cache: false, dataType: "json", timeout: timeout }) .done(onSuccess) .fail(function(xhr, status, error) { if (tryCount < retryLimit) { // 未达到重试上限,重新发起请求 executeRequest(tryCount + 1); } else { // 重试耗尽,执行自定义错误处理 onError(xhr, status, error); } }); } // 首次发起请求 executeRequest(); }
简化原有业务函数
原来的dosomething1和dosomething2只需调用通用函数并传入各自的业务逻辑:
function dosomething1(req) { makeApiRequest(req, do_very_specific1_to_response, handle_very_specific1_to_response); } function dosomething2(req) { makeApiRequest(req, do_very_specific2_to_response, handle_very_specific2_to_response); }
进阶:链式调用兼容方案
如果偏好$.when().then()这类链式语法,可以让通用函数返回jQuery的Deferred Promise,提升灵活性:
function makeApiRequest(req) { const baseUrl = "/api/url"; const timeout = 10000; const retryLimit = 1; const deferred = $.Deferred(); function executeRequest(tryCount = 0) { $.ajax({ type: "POST", url: baseUrl, contentType: "application/json", data: JSON.stringify(req), cache: false, dataType: "json", timeout: timeout }) .done(function(response) { deferred.resolve(response); }) .fail(function(xhr, status, error) { if (tryCount < retryLimit) { executeRequest(tryCount + 1); } else { deferred.reject(xhr, status, error); } }); } executeRequest(); return deferred.promise(); }
调用时使用链式语法:
function dosomething1(req) { makeApiRequest(req) .then(do_very_specific1_to_response) .catch(handle_very_specific1_to_response); } function dosomething2(req) { makeApiRequest(req) .then(do_very_specific2_to_response) .catch(handle_very_specific2_to_response); }
该方案完全兼容$.when(),支持并行处理多个请求:
$.when( makeApiRequest(req1), makeApiRequest(req2) ).then(function(res1, res2) { // 处理多个请求的成功响应 }).catch(function(xhr, status, error) { // 处理任意请求的失败 });
内容的提问来源于stack exchange,提问作者Sameer Malhotra
相关产品推荐
相关产品推荐

