最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Whats the difference between Q Promise library's .finally() and .done()? - Stack Overflow

programmeradmin1浏览0评论

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
  • What arguments are you passing to .then, .finally and .done? – Bergi Commented Sep 25, 2014 at 12:00
  • I have read the docs, and did not find the answer to be so obvious myself. – Brian Moeskau Commented Sep 26, 2014 at 5:13
  • promise is now part of the JS spec, part of the ECMAScript 2015 (ES6) standard . – Pieter Commented Jul 17, 2015 at 9:12
Add a comment  | 

2 Answers 2

Reset to default 19

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.

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 thens 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.

发布评论

评论列表(0)

  1. 暂无评论