【问题标题】:Why $.when() not wait when the function is completed?为什么 $.when() 函数完成时不等待?
【发布时间】:2016-07-21 01:27:38
【问题描述】:

我只想在执行“removeDocx”函数时更新页面。 但在我的情况下,定时器的超时被认为是“等待”功能的完成。 问题出在哪里,我该如何解决? 有代码示例:

$(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;
}

【问题讨论】:

  • 您正在立即调用wait() 并将其返回值传递给$.when。由于wait 不返回任何内容,您希望它如何工作??
  • 你没有 data 参数到 $.ajax。为什么在没有内容的情况下设置application/json的内容类型?

标签: javascript jquery ajax deferred .when


【解决方案1】:

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

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

现在wait 函数也必须返回一个 deferred(以便它与$.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()

【讨论】:

  • 谢谢。有用!我更清楚使用延迟对象。
  • 但这并不完全正确。如果改为 location.href = location.href;写 location.reload(); - 有一个无限循环。而且我无法通过单击项目按钮来实现此功能。
【解决方案2】:

来自the documentation

jQuery.when( deferreds )
延期
类型:延期
零个或多个 Deferred 对象,或纯 JavaScript 对象。

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

如果将单个参数传递给 jQuery.when() 并且它不是 Deferred 或 Promise,它将被视为已解决的 Deferred,并且任何附加的 doneCallbacks 都将立即执行。

【讨论】:

  • 感谢您的回答。你帮了我。
猜你喜欢
  • 2017-08-12
  • 1970-01-01
  • 2014-02-19
  • 2020-06-08
  • 2019-12-18
  • 2013-10-14
  • 1970-01-01
  • 2019-06-16
  • 2020-06-10
相关资源
最近更新 更多