Issue
I want a block of code to run after every resolution/rejection of a promise (using $q
in AngularJS 1.6.x).
I know I can do:
myPromise()
.then((response) => {
// Do my important stuff here
})
.catch((response) => {
// Copy code from above
})
As well as this (slightly better):
myPromise()
.catch(() => {})
.then((response) => {
// Do my important stuff here, and only write it once
})
But I just want to write something like:
myPromise()
.finally((response) => {
// Do my important stuff here, only written once
})
But it seems .finally()
will not run without a then() or catch() block handling the resolution/rejection first.
Any way to do this?
Solution
You can do this, but the question is why and not how
.finally()
in fact will run even if there is no .then()
or .catch()
preceding it. But it's an antipattern to do so because you're avoiding handling errors that could prevent your code from running.
Additionally, since .finally()
does not expose a response or provide a new promise, it is inferior to the other two in utility. The truth is that .finally()
only serves the limited cases it's meant for -- to run code that should execute regardless of the fate of the promise, such as cleaning up variables that are set to indicate to the rest of the application promise hasn't yet returned, for instance.
So although it's not a completely meaningless question, it's not a realistic scenario to be concerned about -- where you would want to run .finally()
without a .then()
or .catch()
.
Answered By - Tony Brasunas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.