是否可以识别/忽略某些拒绝/失败回调? [英] Is possible identify/ignore some reject/fail callback?

查看:110
本文介绍了是否可以识别/忽略某些拒绝/失败回调?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于jQuery.ajax api是$.Deferred()的扩展,因此我试图通过promise模式进行ajax调用,但失败和完成.

Since The jQuery.ajax api is an extension of $.Deferred() i'm trying to make the ajax calls withe the promise schema with fail and done.

$.ajax(..).done(..).fail(..)

并使用它来制作某种Api助手.

And use it to make some kind of Api helper.

function ApiHelper() {

    ...
    this.get = function (path, data) {
        return ajax('GET', path, data);
    };
}

问题:

当前,我需要2种类型的错误处理.有些是全局的,有些是指定的.

Currently, I need 2 types of error handling. Some global and some specify.

如果没有特定的错误,我希望通过全局失败来处理.否则,由定义的一个.

If theres no specific error, i would like handled by the global fail. else, by the defined one.

我想做类似的事情:

apiHelper.get('path/to/api').done(function () {
  //all good
})

function globalHandler() {
  //everything goes wrong. notify here.

}    
apiHelper.get('path/to/api').done(function () {
  //all good
}).fail(function () {
  //everything goes wrong., notify here. and ingnore globalHandler.
})

是否可以确定诺言是否失败,没有人能兑现?还是忽略一些失败的回调?

Is possible identify if the promise fail, and no one handle it? or ignore some fail callback?

推荐答案

如果没有特定的错误,我希望通过全局失败来处理. 否则,由定义的一个.

If theres no specific error, i would like handled by the global fail. else, by the defined one.

注意,.ajaxComplete.ajaxError似乎在之后 .done.fail被称为.

Note, .ajaxComplete, .ajaxError appear to be called after .done or .fail.

尝试设置已处理错误的标志handled;利用 .ajaxComplete

Try setting flag for handled errors handled ; utilizing .ajaxComplete $.ajaxSetup()

var handled = false;

$.ajaxSetup({
    error: function (jqxhr, textStatus, errorThrown) {
        console.log("ajaxSetup:", errorThrown);
        // set , reset `handled` flag here
        handled = true
    }
});
// returns  error
var request = $.post("/echo/jsons/", {
    json: JSON.stringify(["abc"])
});
request.done(function (data) {
    console.log(data)
});
request.fail(function (jqxhr, textStatus, errorThrown) {
    if (!handled) {
        console.log("fail:", errorThrown)
    } else {
        console.log(handled);
    }
});

jsfiddle http://jsfiddle.net/o8gsdyaj/

jsfiddle http://jsfiddle.net/o8gsdyaj/

这篇关于是否可以识别/忽略某些拒绝/失败回调?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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