繁体   English   中英

使用JQuery,如何在继续进行之前等待AJAX​​调用及其回调完成?

[英]Using JQuery, how to wait for both an AJAX call and its callback to finish before proceeding?

我的问题似乎与类似,但我无法通过这些答案解决。

简而言之,在页面加载时,ajax调用会生成一个下拉选择元素,然后根据某些参数设置其默认值。
该代码是这样的:

getList('country', null, q, 'category:customer', null);  
newReportSelection.apply($("#report"));  

function getList(field, val, q, fq, default_value) {
    $.get(... {  
      // call info
    },  function(result) {
      // appending the dropdown to DOM
    });
};

newReportSelection = function () {
    // determine and select default option
}  

getList在各个地方都使用过,因此我无法将此(特定于页面加载)newReportSelection()代码添加到ajax回调函数中。
在getList()调用周围放一个承诺不会等待Ajax调用,因为它是异步的。
将一个放在Ajax调用周围等待它被发送,但是不等待回调函数被执行。
在回调函数中放一个也不可行,因为Ajax部分正在等待它,但是由于异步性,getList()继续进行。

即使在Ajax调用上链承诺和回调函数都能正常工作,这看起来也很脏,而且是不受欢迎的。
有没有办法让newReportSelection()调用等到整个getList()完成,而无需手动将Ajax调用设置为async: false

提前致谢。

从$ .get返回延期/应付款

function getList(field, val, q, fq, default_value) {
  return $.get(... {  
    // call info
  },  function(result) {
    // appending the dropdown to DOM
  });
};     

那么您可以在promise .done()方法中调用后续操作:

getList('country', null, q, 'category:customer', null).done(function() {
    newReportSelection.apply($("#report")); 
});
var d1 = $.Deferred();
var d2 = $.Deferred();
var d3 = $.Deferred();

$.when( d1, d2, d3 ).done(function ( v1, v2, v3 ) {
  console.log( v1 ); // v1 is undefined
  console.log( v2 ); // v2 is "abc"
  console.log( v3 ); // v3 is an array [ 1, 2, 3, 4, 5 ]
});

d1.resolve();
d2.resolve( "abc" );
d3.resolve( 1, 2, 3, 4, 5 );

https://api.jquery.com/jquery.when/中提取

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM