1

I'm using nodejs and was wondering when should I use Q defer, and when just use Promise.resolve/reject?

I saw a lot of examples of both kinds, for example:

// with Q defer
fucntion oneWay(myVal) {
  var deffered = Q.defer();
  if (myVal < 0) {
    deffered.reject(new Error('nope'));
  } else {
    deffered.resolve('yay');
  }
  return deffered.promise;
}

// native Promise
fucntion orAnother(myVal) {
  if (myVal < 0) {
    return Promise.reject(new Error('nope'));
  } else {
    return Promise.resolve('yay');
  }
}

What's the difference, and when is a good practice to use difer?

Is there any difference between Promise.resolve/reject (native) and Q.resolve/reject? They both return promise but it looks different when I look at the return value in node console.

Thanks

arieljannai
  • 2,124
  • 3
  • 19
  • 39
  • It's not clear the context (frontend FW as Angular, node app etc) and what are you referencing with Promise (native ES6 promises, a libray like Bluebird?) – Alessandro Loziobiz Bisi Feb 10 '16 at 10:24
  • you're right. I've made it clearer (node and native promise) – arieljannai Feb 10 '16 at 10:31
  • 1
    They're more or less alternative implementation of the same idea. Use whichever you prefer. – deceze Feb 10 '16 at 10:36
  • If you have access to native promises I suggest you to use it and do not import an external lib to just do something you can accomplish without it. If you need some more promise features take a look at [Bluebird](http://bluebirdjs.com/) or [When](https://github.com/cujojs/when) libs – Alessandro Loziobiz Bisi Feb 10 '16 at 10:44

1 Answers1

2

There is no reason to use the Promise constructor, or - worse - a deferred, when you don't need to. There's nothing asynchronous in your functions, so you don't need (and should not use) callbacks.

Just go for Promise.resolve/Promise.reject or their Q counterparts and construct a promise of a value directly. It's much shorter and simpler anyway.

See also Promise constructor with reject call vs throwing error.

When is a good practice to use defer?

Never. Even in Q, you should use Q.Promise.

Is there any difference between Promise (native) and Q? They look different when I look at the return value in node console.

Well, they're different classes, with different properties, and Q promises do have more methods.
They do work the same though, and are completely interoperable with each other.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375