因此,截至 2016 年,在 API 中使用 jQuery ajax 最简洁的方法是返回一个 Promise。但是,您无法确定调用者是否已将错误处理程序附加到 Promise。
因此,我建议您只需向函数添加一个新参数,告诉函数不要应用默认错误处理,因为调用者将负责错误处理。而且,我建议您通过使用现有的承诺来避免承诺反模式$.ajax()
已经返回而不是创建您自己的延迟:
function request(method, uri, params, proxies, skipDefaultErrorHandling){
// default error handling will be used if nothing is passed
// for skipDefaultErrorHandling
var p = $.ajax({
data: method=='GET'?params:JSON.stringify(params),
contentType: 'application/json',
dataType: 'json',
url: api.root + uri,
type: method,
xhrFields: {
withCredentials: true
}
});
if (!skipDefaultErrorHandling) {
// apply default error handling
p = p.then(null, function(jqXHR, textStatus, errorThrown) {
// put here whatever you want the default error handling to be
// then return the rejection with the various error parameters available
return $.Deferred().reject([jqXHR, textStatus, errorThrown]);
});
}
return p;
};
然后,调用者只需决定是否应用自己的错误处理:
request(...).then(function(data) {
// success code here
});
或者,你可以不做任何承诺failHandler
您传入的回调和您的默认错误处理会查看是否failHandler
是否通过。这是承诺和回调的混合体,不是我通常会选择构建的东西,但由于你的问题要求的是承诺不支持的东西,这是实现这一点的方法之一:
function request(method, uri, params, proxies, failHandler){
// default error handling will be used if nothing is passed
// for skipDefaultErrorHandling
var p = $.ajax({
data: method=='GET'?params:JSON.stringify(params),
contentType: 'application/json',
dataType: 'json',
url: api.root + uri,
type: method,
xhrFields: {
withCredentials: true
}
});
// apply default error handling
p = p.then(null, function(jqXHR, textStatus, errorThrown) {
if (failHandler) {
// call passed in error handling
failHandler.apply(this, arguments);
} else {
// do your default error handling here
}
// then keep the promise rejected so the caller doesn't think it
// succeeded when it actually failed
return $.Deferred().reject([jqXHR, textStatus, errorThrown]);
});
return p;
};