What is the difference between using the Nodejs Q promise library's .finally() and .done() statements.
For example whats the difference between these two?
Q(...)
.then(...)
.finally(); //or fin()
Q(..)
.then()
.done();
What is the difference between using the Nodejs Q promise library's .finally() and .done() statements.
For example whats the difference between these two?
Q(...)
.then(...)
.finally(); //or fin()
Q(..)
.then()
.done();
Share
Improve this question
edited Oct 26, 2016 at 21:55
islandlinux
195 bronze badges
asked Sep 25, 2014 at 5:12
Todd BluhmTodd Bluhm
1952 silver badges9 bronze badges
3
|
2 Answers
Reset to default 19promise.done(onSuccess, onError)
simply allows you to process resolved value. An additional benefit is that does not imply any error swallowing (as it is the case with promise.then()
), it guarantees that any involved exception would be exposed. It also effectively ends the chain and does not return any further promise.
promise.finally(fn)
is for registering a task that must be done after a given promise resolves (it doesn't matter whether promise succeeds or fails). Usually, you use it for some kind of cleanup operations e.g. imagine you set up a progress bar, that needs to be hidden after the request is done (no matter if it was successful), then just do promise.finally(hideProgressBar)
. Additionally promise.finally()
returns input promise, so you can return it for further processing.
The difference is in chaining and error handling, and error logging:
Q(...)
.then(...)
.finally();
Here, if the then
throws, the finally
will still run, but no error will log. In Q finally
is run regardless of the .then
being successful or not. This is like the finally
keyword in JS try/catch/finally
. It is also possible to chain additional then
s to the chain in this case.
Q(..)
.then()
.done();
Here, done
indicates that the promise chain has ended, you can not chain to it any more. If you pass it only an onFulfilled handler it will not run if the then
threw, and it will log errors if it ends with an exception.
.then
,.finally
and.done
? – Bergi Commented Sep 25, 2014 at 12:00