在jQuery的延迟对象中抛出错误 [英] Throwing an Error in jQuery's Deferred object

查看:126
本文介绍了在jQuery的延迟对象中抛出错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 $。ajax 承诺,并希望检查我的(语法有效的)响应是否包含一个错误,触发被拒绝的状态在这种情况。

I have an $.ajax promise and want to check whether my (syntactically valid) response contains an error, triggering the rejected status in that case.

我已经与我自己的承诺库轻松处理这些任务。我不喜欢jQuery的承诺缓存)实现与其 Deferred object ,可能忽视了一些东西,因为我很少使用它。我想要走的路上只是使用 .then() ,这似乎相当复杂:

I have worked with my own promise library which deals such tasks easily. I do not really like jQuery's Promise (cache) implementation with its Deferred object and may have overlooked something, because I seldom use it. I think the way to go is just using .then(), which seems to be rather complicated:

return $.ajax(...).then(function success(response) {
    var problem = hasError(response);
    if (problem) {
        var error = new $.Deferred;
        error.reject(problem);
        return error;
    } else
        return response;
});

这应该返回在网络错误或响应问题的情况下被拒绝的承诺。但是返回被拒绝的延期真的是[唯一|最好|最短]的方式吗?

This should return a promise which is rejected in case of network errors or problems with the response. But is returning a rejected deferred really the [only|best|shortest] way to go?

我还将提供如何处理这种错误抛出响应的帮助处理程序在ajax选项中,我找不到关于他们的良好文档。

I also would appriciate help on how to deal with such "error-throwing response handlers" in the ajax options themselfes, I could not find good documentation about them.

免责声明:不,我不能更改服务器响应。问题检测方法是同步的。我不想使用其他库,我对jQuery解决这个问题的方式特别感兴趣。

Disclaimer: No, I cant change the server responses. The problem-detecting method is synchronous. I don't want to use other libraries, I'm particularly interested in the way jQuery solves this.

推荐答案

现在更新为jQuery 1.8 +

解决此问题的最简单的方法是运行 $。ajax 通过 .then 根据数据的成功或失败进行过滤。

The easiest way to tackle this is to run the response of $.ajax through .then to filter based on success or failure of the data.

$.ajax()
    .then(function (response) {
        return $.Deferred(function (deferred) {
            var problem = hasError(response);

            if (problem) {
                return deferred.reject(problem)
            }

            deferred.resolve(response);
        }).promise();
    });

然后,您可以将这个新承诺退回到任何调用代码将消耗这一点:

You could then return this new promise to whatever calling code would consume this:

var request = function () {
    return $.ajax()
        .then(function (response) {
            return $.Deferred(function (deferred) {
                var problem = hasError(response);

                if (problem) {
                    return deferred.reject(problem)
                }

                deferred.resolve(response);
            }).promise();
        });
};

request()
    .done(function (response) {
        // handle success
    })
    .fail(function (problem) {
        // handle failure
    });

这篇关于在jQuery的延迟对象中抛出错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆