You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何控制异步函数执行顺序,确保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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 05:18:00