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();
.done () terminates the promise chain, making sure nothing else can attach further steps. This means that the jQuery promise implementation can throw any unhandled exception, since no one can possible handle it using .fail (). In practical terms, if you do not plan to attach more steps to a promise, you should use .done ().
.then () always returns a NEW Promise, and you are in charge of controlling what that Promise is based on what the function you passed it returned.
If a function cannot return a value or throw an exception without blocking, it can return a promise instead. A promise is an object that represents the return value or the thrown exception that the function may eventually provide.
I forgot to mention, if you return a Promise instead of atomic type value, the outer promise will wait until inner promise resolves: Show activity on this post. so it is up to you what you must do... do you care if it succeeds or if it fails?
promise.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With