【问题标题】:jquery deferred and return false based on server response [duplicate]jquery延迟并根据服务器响应返回false [重复]
【发布时间】:2017-04-13 13:05:04
【问题描述】:

我有下面的 jquery 延迟逻辑。

var $qCallA = callA();
var $qCallB = callB();

$.when($qCallA,$qCallB).then(function () {
        $("#spinnerDiv").removeClass('spinner show');
});

function callA() {
    return $.getJSON("/callA", function (data) {
        if (data.status === "success") {
            buildTable1(data);
        }
    });
}

function callB() {
    return $.getJSON("/callB", function (data) {
        if (data.status === "success") {
            buildTable2(data);
        }
    });
}

我想根据来自后端 json 的响应为 $.getJSON 调用返回 false。 例如,如果 data.status == "failure" 那么我想为 getJSON 返回 "false"。 如何做到这一点?

谢谢

【问题讨论】:

  • 你不能从异步函数返回任何东西。当data.status == 'failure' 发生时,你到底需要做什么?
  • 你不能从异步调用中返回......你想要让承诺失败吗?
  • 是的。我想兑现诺言。
  • @JavaUser 赏金有什么用?我的回答中是否缺少任何内容,对您不起作用吗?

标签: javascript jquery jquery-deferred


【解决方案1】:

您应该为您的$.getJSON 提供成功回调then,并为$.when 返回自定义Deffered 以进行处理。

这样您就可以根据 JSON 中的数据手动解决或拒绝。

var $qCallA = callA();
var $qCallB = callB();

$.when($qCallA,$qCallB).then(function (s1, s2) {
    $("#spinnerDiv").removeClass('spinner show');
}).fail(function() {
    //handle failure
});

function callA() {
    return $.getJSON("/callA").then(function (data) {
        if (data.status === 'failure') {
        return $.Deferred().reject("A: no success");
      }
      return $.Deferred().resolve(data);      
    });
}

function callB() {
    return $.getJSON("/callB").then(function (data) {
        if (data.status === 'success') {
        return $.Deferred().resolve(data);
      }
      return $.Deferred().reject("B: no success");
    });
}

Similar JSFiddle

【讨论】:

    【解决方案2】:

    听起来您想使用正确的then 回调,您可以在其中为承诺返回一个新的结果值:

    $.when(callA(), callB()).then(function(a, b) {
        $("#spinnerDiv").removeClass('spinner show');
        if (a && b) …
    });
    
    function callA() {
        return $.getJSON("/callA").then(function(data) {
            if (data.status === "success") {
                buildTable1(data);
            }
            return data.status != "failure";
        });
    }
    
    function callB() {
        return $.getJSON("/callB").then(function(data) {
            if (data.status === "success") {
                buildTable2(data);
            }
            return data.status != "failure";
        });
    }
    

    【讨论】:

      猜你喜欢
      • 2018-05-19
      • 1970-01-01
      • 2014-04-09
      • 2011-09-26
      • 1970-01-01
      • 1970-01-01
      • 2016-10-09
      • 2018-08-09
      • 2013-01-02
      相关资源
      最近更新 更多