正在等待异步调用,无法使用ajax

Waiting on asynchronous call not working with ajax

本文关键字:ajax 在等待 异步 调用      更新时间:2023-09-26

我使用deferred来等待大约两个函数完成(它们提供模板并显示结果),然后再提供模板中的select。

当一个选项卡显示时,我会。

var notAssociateContact = getNotAssociateContact();
var associateContact = getAssociateContact();
$.when(notAssociateContact, associateContact).then(assignLocationToSelector($("select[name=locationIds''['']]")));
function getNotAssociateContact() {
    var deferred = $.ajax({
        type: "GET",
        url: "http://localhost:8080/rest/contacts/notassociatedto/" + $("#lodgerId").val(),
        success: function(data, status, jqXHR) {
            $("#lodgerContactAvailableDivTemplate").empty();
            if (data.length != 0) {
               $("#lodgerContactAvailableDivTemplate").append(templateLodgerContactAvailable(data));
                $('#lodgerContactAvailableTableResult').bootstrapTable();
            }
        },
        error: function(jqXHR, status) {
            // error handler
            alert("error " + jqXHR + " -  " + status);
        }
    }).then(function(response) {
        // optional callback to handle this response 
    });
    return deferred;
}

function getAssociateContact() {
    var deferred = $.ajax({
        type: "GET",
        url: "http://localhost:8080/rest/lodgers/" + $("#lodgerId").val() + "/contacts",
        success: function(data, status, jqXHR) {
            $("#lodgerContactDivTemplate").empty();
            if (data.length != 0) {
                $("#lodgerContactDivTemplate").append(templateLodgerContact(data));
                $('#lodgerContactTableResult').bootstrapTable();
                //  $('#lodgerContactTableResult tr').bind("dblclick", null, contactReferenceSelectedRow);
            }
        },
        error: function(jqXHR, status) {
            // error handler
            alert("error " + jqXHR + " -  " + status);
        }
    }).then(function(response) {
        // optional callback to handle this response 
    });
    return deferred;
}

我没有得到任何错误,但assignLocationToSelector与运行不一样。Select为空。

在控制台中,如果我运行

assignLocationToSelector($("select[name=locationIds''['']]"));

选择已正确馈送。

当我调试并到达$.When时,我看到两个ajax调用正在挂起。。。

所以延期似乎有问题。

您的$.when().then()需要传递一个函数引用。您正在立即调用一个函数,然后传递返回结果。这会立即执行函数,而不允许$.when()稍后调用它。

将您的$.when()语句从以下内容更改为:

$.when(notAssociateContact, associateContact).then(assignLocationToSelector($("select[name=locationIds''['']]")));

到此:

$.when(notAssociateContact, associateContact).then(function() {   
   assignLocationToSelector($("select[name=locationIds''['']]"));
});