admin管理员组文章数量:1246630
An example to make clear what i want to do. This is what I would usually do:
function success(data, status, jqxhr){
if ( data.error )
return failure(jqxhr, status, data.error);
// process data
}
function failure(jqxhr, status, err){
...
}
$.ajax( ... )
.done(success)
.fail(failure)
Is there any way, i can acplish this with anonymous functions only, like so?
$.ajax( ... )
.done(function(data, status, jqxhr){
if(data.error)
// what do i need to do here to jump in to the fail handler?
})
.fail(function(jqxhr, status, err){
...
})
An example to make clear what i want to do. This is what I would usually do:
function success(data, status, jqxhr){
if ( data.error )
return failure(jqxhr, status, data.error);
// process data
}
function failure(jqxhr, status, err){
...
}
$.ajax( ... )
.done(success)
.fail(failure)
Is there any way, i can acplish this with anonymous functions only, like so?
$.ajax( ... )
.done(function(data, status, jqxhr){
if(data.error)
// what do i need to do here to jump in to the fail handler?
})
.fail(function(jqxhr, status, err){
...
})
Share
Improve this question
asked Jan 14, 2014 at 10:09
lordvladlordvlad
5,3472 gold badges25 silver badges44 bronze badges
11
- 1 a Deferred object's state can be set only once.... – Arun P Johny Commented Jan 14, 2014 at 10:11
- I know that. Is there still any way to force the execution of failure handlers? – lordvlad Commented Jan 14, 2014 at 10:13
- technically you can use a goto. But in practice it's better not to do it – Fabrizio Calderan Commented Jan 14, 2014 at 10:13
-
2
What about using
.always()
? – Nabil Kadimi Commented Jan 14, 2014 at 10:18 - @NabilKadimi, then i would need an additional check, whether always was called after a success or failure, but it's an idea – lordvlad Commented Jan 14, 2014 at 10:26
1 Answer
Reset to default 16what do i need to do here to jump in to the fail handler?
Don't use done
, but then
to map over the result of the promise. By returning a rejected promise you can "throw" an error and reject the resulting promise, so that your fail handler is executed.
$.ajax(…)
.then(function(data, status, jqxhr){
if (data.error)
return $.Deferred().reject(data.error);
else
return data; // if you want to return multiple arguments, you'd use
// $.Deferred().resolve(data, status, jqxhr);
})
.done(function(data) {
…
})
.fail(function(jqxhr, status, err){
…
});
版权声明:本文标题:javascript - Can I force jQuery DeferredAjax to execute fail handler after it has been resolved? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740267373a2251419.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论