Search code examples
javascriptasynchronouspromisedeferred

Is there any situation where it is impossible to use a Promise and a Deferred must be used?


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.


Solution

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