如何控制异步函数执行顺序,确保refreshBirths在前序接口请求完成后调用
解决方案
核心问题是你当前的getDictionaryMother、getDictionaryFather没有返回Ajax请求的Deferred对象,导致$.when无法感知请求是否完成,同时你原来的写法还重复发起了getDictionaryFather请求,按以下两步调整即可:
1. 改造两个字典请求函数,返回Ajax实例
两个函数都新增return语句返回Ajax的Deferred对象,同时删除函数内部的refreshBirths调用,只保留本身的渲染逻辑:
function getDictionaryMother() { // 新增return返回Ajax对象 return $.ajax({ url: "/admin/api/dictionary/" + "ANIMAL_MOTHER", type: "GET", dataType: "json" }) .done(function(response) { $('#mother-create').empty(); $('#mother').empty(); response.forEach(function(mother){ $('#mother-create').append('<option value='+ mother.id +'> '+ mother.value +' </option>'); $('#mother').append('<option value='+ mother.id +'> '+ mother.value +' </option>'); }); }) .fail(function(jqxhr, textStatus, errorThrown) { displayErrorInformation("Cannot get dict: ANIMAL_MOTHER due to: " + jqxhr.responseText); }); } // getDictionaryFather做相同改造 function getDictionaryFather() { return $.ajax({ url: "/admin/api/dictionary/" + "ANIMAL_FATHER", type: "GET", dataType: "json" }) .done(function(response) { // 保留原有父本下拉框渲染逻辑 }) .fail(function(jqxhr, textStatus, errorThrown) { displayErrorInformation("Cannot get dict: ANIMAL_FATHER due to: " + jqxhr.responseText); }); }
2. 修改模态框事件回调,统一控制执行时序
用$.when同时监听两个请求的完成状态,两个请求全部成功后再执行refreshBirths:
$('#create-modal').on('shown.bs.modal', function() { refreshBreeds(); // 同时传入两个请求,全部完成后才触发done回调 $.when(getDictionaryMother(), getDictionaryFather()).done(function() { refreshBirths(); }); });
调整后所有执行逻辑都统一在模态框回调中管理,不会散落在各个接口回调中,同时保证refreshBirths执行时母本、父本的ID已经渲染完成可以正常获取。
内容的提问来源于stack exchange,提问作者HappyProgrammer
相关产品推荐
相关产品推荐

