1

I understand on stylistic/clarity grounds that people may prefer one approach over the other but I'm trying to understand if there is any situation that you can not use a Promise and must use a Deferred. For reference I'm using the Q javascript library but I would imagine it would be applicable to any other library and language. I don't believe the explanation under "Deferreds are cool because..." actually describes a case where it is impossible to achieve the same thing with a simple q.Promise() call (and thus you have to use a Deferred) but I wanted to check that is correct.

Are deferreds solely about eliminating the "pyramid of doom" or is there more too them?

This question is interesting but doesn't really tackle this particular question.

Community
  • 1
  • 1
AJP
  • 26,547
  • 23
  • 88
  • 127

1 Answers1

2

No, there is no such case. It is easy to prove that you can do anything you want to do with the promise constructor and not use deferred by showing a translation between them:

 var deferred = {};
 var p = new Q.Promise((resolve, reject){ // always runs sync
     deferred.resolve = resolve;
     deferred.reject = reject;
 });
 deferred.promise = p;

The advantage of the promise constructor is the fact it's throw safe, that is - synchronous throws are converted to rejections which saves you from subtle bugs.

In either case, construction should be used only rarely. Q is a pretty old library too, consider something newer and more modern.

Community
  • 1
  • 1
Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • 1. Great answer, clearly see that you can translate between the two, thanks Benjamin. 2. Great link. I am actually doing "You should only use deferred objects when you are converting an API to promises" because I thought the node MongoClient.connect did not pass back promises. I see that the Typescript definition is just not up to date as it does: ["Returns: Promise if no callback passed](http://mongodb.github.io/node-mongodb-native/2.0/api/MongoClient.html#.connect). 3. Q is old but it seems to work fine, got a recommendation of something better? Thanks again very much :) – AJP Dec 09 '15 at 17:21
  • 1
    @AJP [Bluebird](http://bluebirdjs.com/docs/why-bluebird.html) – idbehold Dec 09 '15 at 18:33
  • Pretty much a duplicate of [When would someone need to create a deferred?](http://stackoverflow.com/questions/32853105/when-would-someone-need-to-create-a-deferred) – jfriend00 Dec 09 '15 at 23:43