When should I use Q.defer and when just Promise.re

2019-08-15 04:03发布

问题:

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

回答1:

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.