0

With deferred (using your library of choice):

const deferred = library.defer();
if (condition) deferred.resolve('success');
else deferred.reject('fail');
deferred.promise.then((result) => console.log(result));

Just wrapping in a promise:

new Promise((resolve, reject) => {
  if (condition) resolve('success');
  else reject('fail');
}).then((result) => console.log(result));

What's the difference between these two scenarios? Is the only real benefit that you don't have to wrap all your code in a promise? If that's the case what's the point of a deferred?

m0meni
  • 16,006
  • 16
  • 82
  • 141
  • 3
    Deferreds are [obsolete](https://developer.mozilla.org/en-US/docs/Mozilla/JavaScript_code_modules/Promise.jsm/Deferred), here's good read up on main reasons why it's better to not use them: https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns#the-deferred-anti-pattern . – bardzusny Dec 20 '15 at 21:34
  • @bardzusny: No, this has nothing to do with the [explicit promise construction antipattern](http://stackoverflow.com/q/23803743/1048572). – Bergi Dec 20 '15 at 23:10

1 Answers1

2

A deferred is an object that has the resolve and reject method, allowing it's state to be changed. A promise doesn't.

As for generating promises in both ways, generally there shouldn't be any difference. I prefer the syntax of Promises since it wraps your logic in a function and avoids polluting the outer scope with variables, but that's about it.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Louay Alakkad
  • 7,132
  • 2
  • 22
  • 45
  • 2
    `new Promise` will also cause the promise to reject if there is a synchronous error, whereas the function containing the deferred could _sometimes_ reject and _sometimes_ throw. – loganfsmyth Dec 20 '15 at 22:02
  • 1
    I thought of that but wasn't sure. Can you please give me a reference? I know it works in `then`s. – Louay Alakkad Dec 20 '15 at 22:03
  • 1
    If you want specifics, http://www.ecma-international.org/ecma-262/6.0/#sec-promise-executor step 10 would be the primary source. – loganfsmyth Dec 20 '15 at 22:32