I\'m trying to wrap my head around the correct way to indicate a failure within a .then()
.
If the promise doesn\'t fail, (I.e. the operation that return
TL;DR: You can use rejections for control flow, but in general they are for exceptional cases only
In the promise version, if the request returns a 404 it will end up in the .catch() immediately right?
Yes.
If data.IsSuccessful==false, then it will also end up in the .catch()?
Yes.
I'm not calling resolve or reject anywhere, is that problematic?
Not at all. You're not using the Promise
constructor (which you don't need, as you already have a promise for the ajax result).
What if I want to treat both failures differently, how would I go about that?
Throw different kinds of errors so that you can distinguish them. Give them names, add special properties, do subclassing (in ES6 especially), or just look at the message.
with promises, if from within the .then(), I want to do something similar, I've been lead to believe that what I should do is throw an error instead
Not necessarily. You can do exactly the same as you did without promises - put an if-else in the callback (or an if with an early return if you prefer).
In terms of control flow and their result values,
.then(function(res) {
if (!res.isOK) {
// do something
return false;
}
// do something else
}).catch(function(err) {
// handle something
})
and
.then(function(res) {
if (!res.isOK)
throw new MyError(res);
// do something else
}).catch(function(err) {
if (err instanceof MyError) {
// do something
return false;
}
// handle something
})
are pretty much equivalent (except for exceptions in do something
and with code other than this throwing MyError
s). The major difference is when you want to chain additional .then(…)
invocations between the then
and catch
. If you don't, just choose whatever you like better.