为什么 $.when() 不等待函数完成?

Why $.when() not wait when the function is completed?

我只想在函数 "removeDocx" 执行时更新页面。 但就我而言,计时器超时被视为 "wait" 函数的完成。 问题出在哪里,我该如何解决? 有代码示例:

$(function () {
  $.when(wait()).done(function () {
        location.href = location.href;
    });
});
function wait() {
    var pm = { ISN_DOC: GetrcId(document.location.href) };
    if (isNaN(pm.ISN_DOC))
        setTimeout(wait, 500);
    else removeDocx();
}
function removeDocx() {
    var def = $.Deferred();
    var url = "MinPrj/Collage.asmx/clearPattern?isn_doc=" + pm.ISN_DOC;
    $.ajax({
        type: 'POST',
        url: rootpath + url,
        contentType: 'application/json'
    }).done(function (r) {
         def.resolve();
    }).fail(def.reject());
    return def;
}

来自the documentation

jQuery.when( deferreds )
deferreds
Type: Deferred
Zero or more Deferred objects, or plain JavaScript objects.

您传递的是常规函数,而不是 Deferred 对象,所以……

If a single argument is passed to jQuery.when() and it is not a Deferred or a Promise, it will be treated as a resolved Deferred and any doneCallbacks attached will be executed immediately.

首先修复你的 removeDocx 函数。 $.ajax 已经 return 是一个延迟对象:

function removeDocx() {
    var url = "MinPrj/Collage.asmx/clearPattern?isn_doc=" + pm.ISN_DOC;
    return $.ajax({
        type: 'POST',
        url: rootpath + url,
        contentType: 'application/json'
    });
}

现在 wait 函数也必须 return 延迟(以便它与 $.when 一起工作)。问题是您必须在对 wait 的不同(伪递归)调用之间共享状态。这样的事情可能会奏效:

function wait(def) {
    if (!def) {
        var def = $.Deferred();
    }
    var pm = { ISN_DOC: GetrcId(document.location.href) };
    if (isNaN(pm.ISN_DOC)) {
        setTimeout(function() {
            wait(def);
        }, 500);
    } else {
        $.when(removeDocx()).then(def.resolve);
    }
    return def;
}

其余代码保持原样,即您调用 wait() 时不带参数。