When should I use Q.defer and when just Promise.resolve/reject?

扶醉桌前 提交于 2019-12-11 10:05:26

问题


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.



来源:https://stackoverflow.com/questions/35312418/when-should-i-use-q-defer-and-when-just-promise-resolve-reject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!