Search code examples
javascriptpromiseecmascript-6deferred

Difference between promise and deferred when wrapping your entire block of code in a promise?


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?


Solution

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