假设我有一个返回promise
的函数。返回的promise将由外部函数检查,以决定如何处理.fail()
条件。
function refreshTimeline() {
var promise = ajaxMethod1()
.then (function (data) {
return ajaxMethod2()
})
.then(function(json) {
//...
});
return promise;
}
function outerFunction() {
refreshTimeline
.then(function() {
//...
})
.fail(function(jqXHR, textStatus, errorThrown) {
// This will handle any errors in the chain *including* the refreshTimeline
});
}
我的问题是我需要在refreshTimeline()中抛出一个自定义业务异常,它应该被外部函数捕获,就像任何常规的Ajax错误一样。目标是让outerFunction fail()
获得此异常,并且可能以特殊方式处理它(可能需要识别它)。
但以下情况并不奏效:
function refreshTimeline() {
var promise = ajaxMethod1()
.then (function (data) {
return ajaxMethod2()
})
.then(function(json) {
if (someBusinessCondition(json) {
// throw custom exception
throw "MyException"; //JS gives "Uncaught" msg
}
});
return promise;
}
所以,我不想在refreshTimeline()
中自己处理这个业务错误(因为它不是这个效用函数的工作 - 它只是向下游转发错误)而我想要将其传播到外部错误处理程序,这将处理常规.fail()
。这可能吗?
答案 0 :(得分:1)
不是抛出异常,而是使用您的字符串/ Exception /任何对象作为参数返回被拒绝的deferred / promise实例。
function refreshTimeline() {
var promise = ajaxMethod1()
.then (function (data) {
return ajaxMethod2();
})
.then(function(json) {
if (someBusinessCondition(json) {
// return your error as a rejected (failed) promise
return $.Deferred().reject("MyException");
}
});
return promise;
}
这将使用.fail()
作为第一个参数(您将其命名为"MyException"
)的值调用外部jqXHR
。
答案 1 :(得分:1)
似乎jQuery 3在Jun 2016上发布了,也许现在是时候使用它了,因为它推迟了它实际上就像promises一样。
jQuery.Deferred().resolve(22)
.then(
result=>{
console.log("got result:",result);
throw("rejecting");
}
).catch(
err=>console.warn("got the error:",err)
)

<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
&#13;
或者你可以使用旧的jQuery(一个正确的polyfilled)Promise:
Promise.resolve(22)//starting an actual promise chain (not badly behaving deferred)
.then(
//returning the defected deferred does not affect promise chain
// promise will handle it as a promise like and then returns an actual promise
result=>jQuery.Deferred().resolve(result)
)
.then(
result=>{
console.log("got result:",result);
throw("whatever reason your code throws");
}
)
.catch(
err=>console.warn("error caught:",err)
)
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;