我什么时候应该使用Q.defer以及何时Promise.resolve / reject? [英] When should I use Q.defer and when just Promise.resolve/reject?

查看:179
本文介绍了我什么时候应该使用Q.defer以及何时Promise.resolve / reject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用nodejs,想知道何时应该使用 Q 延迟,何时使用Promise .resolve / reject?

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?

Promise.resolve / reject(本机)与Q.resolve / reject之间是否有区别?它们都返回promise,但是当我在节点控制台中查看返回值时,它们看起来有所不同。

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.

谢谢

推荐答案

没有理由使用 Promise 构造函数,或者-更糟-不需要的时候推迟。函数中没有异步的东西,因此您不需要(也不应该使用)回调。

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.

只需执行 Promise.resolve / Promise.reject 或它们的 Q 对应对象,并直接构造一个价值承诺。

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.

另请参见通过拒绝调用与抛出错误


什么时候使用延迟?

When is a good practice to use defer?

从不。即使在 Q 中,也应使用 Q.Promise

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


是Promise(本机)和Q之间有什么区别?当我在节点控制台中查看返回值时,它们看起来有所不同。

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

嗯,它们是不同的类,具有不同的属性,并且 Q 许诺确实有更多的方法。

它们的工作原理相同,并且可以完全互操作。

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.

这篇关于我什么时候应该使用Q.defer以及何时Promise.resolve / reject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆