如何正确封装并 await jQuery AJAX 调用以实现代码复用

2次阅读

如何正确封装并 await jQuery AJAX 调用以实现代码复用

本文详解为何直接 await 自定义 ajax 封装函数会失效,核心在于函数未返回 promise;通过修正 makecall 返回 $.ajax() 实例,并统一使用 async/await 风格,可安全链式调用并避免执行中断。

javaScript(尤其是使用 jquery 的项目)中,为避免重复编写 AJAX 逻辑而封装通用请求函数是常见做法。但若封装不当,极易引发“调用不执行”“Promise 未等待”“TS 类型警告(如 await has no effect)”等问题——这正是你遇到的核心问题。

❌ 错误封装:函数不返回 Promise,await 失效

原始 makeCall 函数如下:

const makeCall = (url, type, data, done) => {   $.ajax({     url, type, dataType: "json", data   })   .done(done)   .fail(console.error); }; // ⚠️ 没有 return!函数返回 undefined

此时 await makeCall(…) 实际是在 await undefined —— 这既无意义,也不触发等待,typescript 直接报出 ts(80007) 警告。后续依赖该响应的代码(如 retrieveCountry.php 请求)自然不会按预期执行。

✅ 正确封装:返回 $.ajax() 的 Promise,并移除副作用回调

$.ajax() 本身返回一个 Deferred 对象(兼容 Promise),可被 await 或 .then() 消费。因此,makeCall 应直接返回它,并将业务逻辑(如填充 detail)移至调用处处理,而非耦合在封装函数内:

// ✅ 正确:返回 Promise,支持 await const makeCall = (url, type = "GET", data = {}) => {   return $.ajax({     url,     type,     dataType: "json",     data   }); };

? 注意:done 回调已移除。现代 Promise 风格下,应由调用方统一用 await 或 .then() 处理成功逻辑,保持职责单一。

✅ 完整修复后的异步流程(推荐 async/await)

假设整个逻辑位于一个 async 函数中(如 initGeolocation()),修正后如下:

const detail = {}; // 局部作用域对象,安全  try {   // ✅ 第一步:await 获取国家信息   const opencageResponse = await makeCall("libs/php/opencage.php", "GET", {     LAT: x.coords.latitude,     LNG: x.coords.longitude   });    if (opencageResponse.status?.name === "ok") {     // 填充 detail(纯同步操作)     detail.lat = x.coords.latitude;     detail.long = x.coords.longitude;     detail.continent = opencageResponse.data.results[0].components.continent;     detail.countryName = opencageResponse.data.results[0].components.country;     detail.countryCode = opencageResponse.data.results[0].components.country_code;      // 更新 UI     const code = detail.countryCode;     console.log("Detected country code:", code);     $("#countrySelect").val(code.toUpperCase());   } else {     throw new Error("OpenCage API returned non-ok status");   }    // ✅ 第二步:基于上一步结果,发起第二个请求   const geojsonResponse = await makeCall("libs/php/retrieveCountry.php", "GET", {     code: detail.countryCode.toUpperCase()   });    // ✅ 成功添加 GeoJSON 到地图   L.geoJSON(geojsonResponse).addTo(map);  } catch (error) {   console.error("AJAX chain failed:", error);   // 可在此统一处理错误(如显示提示、降级逻辑等) }

? 关键要点总结

  • await 只对 Promise 有效:确保封装函数 return 一个 Promise(如 $.ajax() 返回值),而非仅执行它。
  • 避免混合风格:不要在封装函数中同时用 .done() 和 await,易导致时序混乱与资源竞争。
  • 错误处理集中化:使用 try/catch 捕获整个链路异常,比分散 .fail() 更清晰健壮。
  • 类型安全建议(TS 用户):为 makeCall 添加返回类型注解:
    const makeCall = (url: string, type?: string, data?: Record): Promise => {   return $.ajax({ url, type, dataType: "json", data }); };

通过以上重构,你的 AJAX 调用既满足 DRY 原则,又完全兼容 async/await 语义,彻底解决“第二请求不执行”和 TypeScript 警告问题。

text=ZqhQzanResources