什么时候不按预期工作

when and then are not working as expected

调用AJAX函数并等待AJAX函数完成。

$.when(updateApplication("about_you"))
    .then(function() {
        console.log("when is working perfectly :          ");
    });


function updateApplication(){
    //some code here

    // ajax call update the application and get response back like if applications is updated successfully or not with true/false status.

    return $.ajax({
            type: 'POST',
            url: base_url,
            data: {json: data},
            dataType: 'json'
        }).done( function( data ) {
            return data;
        }).fail({
            return data;    
        });
}

$.when 调用 AJAX 函数,AJAX 函数完美运行,但 $.when 中的代码不执行。 (console.log 从不打印)

尝试了 $.when 完成

    $.when(updateApplication("about_you")).then(function(){
        console.log("when is working perfectly :          ");
    }).done(function(data){
        console.log("see if it works  :          ");
    });

仍然没有 console.log 起作用,换句话说 $.when body 从不执行

调用时再次尝试

    $.when(updateApplication("about_you")).done(function(data){
        console.log("see if it works  :          ");
    });

仍然console.log 不打印。知道打电话有什么问题。需要修复什么才能执行 $.when once ajax call finish.

您已经在处理 updateApplication 中的 ajax,您需要删除对 done 的使用,以便在正确时使用:

function updateApplication(){
  //some code here

  // ajax call update the application and get response back like if applications is updated successfully or not with true/false status.

  return $.ajax({
        type: 'POST',
        url: base_url,
        data: {json: data},
        dataType: 'json'
    });
}

如果您仍然没有得到任何类型的响应,您可能需要先检查是否失败,然后再链接 .then:

$.when(updateApplication("about_you"))
    .fail(function(){ alert('Failed!'); })
    .then(function(){ alert('Success!'); });

另请注意,如果您打算在此处结束承诺链,则此处的 then 可能可以替换为 donethen()pipe() 的别名,returns 是一个新的承诺,而 done 只是 returns 一个无法链接的成功对象

更多信息在这里:jQuery deferreds and promises - .then() vs .done()