首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >$.Deferred不推迟

$.Deferred不推迟
EN

Stack Overflow用户
提问于 2014-03-18 12:10:54
回答 1查看 58关注 0票数 0

当我在调试器中遍历mys代码时,我可以看到var答案,给出了我所期望的结果,但是当函数完成时,它显示为未定义的。有人能帮我指出正确的方向吗?我已经看过医生了,我看不出哪里出了问题。守则如下:

代码语言:javascript
复制
function hasTimeAccountData(aktivEmployee) {
        this.aktivEmployee = aktivEmployee;
        var deferred = new $.Deferred();
        callService("GetEmployee",
            { employeeNo: aktivEmployee.id},
            function (result) {
                var answer = result.HasTimeAccountData;
                deferred.resolve(answer);
            });
        return deferred.promise();
    }

function callService(functionName, data, onSuccess, onTimeout) {
    var timeout;
    if (onTimeout) timeout = setTimeout(onTimeout, 10000);
    var server = lStorage.getServerUrl();
    if (!server) server = getDefaultAddress();
    var url = server + functionName;
    $.ajax({
        dataType: "jsonp",
        url: url,
        data: data,
        success: function (data) {
            clearTimeout(timeout);
            if (onSuccess) onSuccess(data);
        }
    });
}

提前感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-03-18 13:20:45

我认为重要的是要记住,hasTimeAccountData正在返回一个承诺,因此不能立即评估它是否会返回该承诺的成功结果。因此,您在注释(hasTimeAccountData(employee)===false)中包含的代码将无法工作。

您需要使用诺言对象的方法,并引入回调,以响应该承诺的不同结果。即。

代码语言:javascript
复制
hasTimeAccountData(employee)
        .then(showEmployeeData, showErrorMessage);

这里是一个详细的测试用例小提琴。,我把它放在一起,向您展示了一种方法,您可以对承诺的不同结果做出反应。我已经扩展了hasTimeAccountData,当事情出错的时候,我也会引用拒绝承诺的话.

代码语言:javascript
复制
function hasTimeAccountData(aktivEmployee) {
    var deferred = new $.Deferred();    

    this.aktivEmployee = aktivEmployee;

    callService(
        "GetEmployee", 
        { employeeNo: aktivEmployee.id },
        function success(result) {
            if (result.hasOwnProperty("HasTimeAccountData")) {
                deferred.resolve(result.HasTimeAccountData);
            }
            else {
                deferred.reject("no time account data field in return data!");
            }
        },
        function timeout() {
            deferred.reject("timeout occurred");
        }
    );

    return deferred.promise();
}

为了说明这一点,我模拟了callService方法。

我希望这有帮助,如果不检查关于这个的jQuery文档,他们真的很好。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/22478996

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档