Jquery Deferred Reject Immediately
When using JQuery.Deferred is it OK to invoke reject() directly? Without having invoked a async function? Perhaps I want some kind of test in the beginning of my async function. If
Solution 1:
When using JQuery.Deferred is it OK to invoke reject() directly? Without having invoked a async function?
Yes, it's totally OK to return an already rejected promise, and to reject deferreds immediately. You only might need to verify that your callbacks don't rely on asynchronous resolution, which jQuery does not guarantee (in contrast to A+ implementations).
Notice that in your code you should use then
instead of manually resolving the deferred:
functiondoSomethingAsync() {
var testFailed = /* Test if the ajax call should be invoked */;
var dfd = testFailed
? $.Deferred().reject('test failed')
: $.get('/api/testapi/get');
return dfd.then(function (data) {
return {
success: true,
data: data
};
}, function (err) {
return {
success: false,
data: err
};
});
}
Solution 2:
You can do it quickly, as your function return a Promise object:
returnPromise.reject('test failed');
Post a Comment for "Jquery Deferred Reject Immediately"