【问题标题】:Difference between Q.defer() & Promise()Q.defer() 和 Promise() 的区别
【发布时间】:2017-05-23 07:18:46
【问题描述】:

我试图理解为什么下面的代码与 Q.defer() 和 Promise() 表现不同

案例1:当我使用Q.defer()时

getDocument(id)
.then(function (response) {
   console.log('in first then')
   return 'from two';
}).then(function (response) {
   console.log(response)
});

var getDocument=function(){
  var b = Q.defer();
    b.resolve('from getDocument'); // here will do some async operation..this is just an example
  return b.promise;
}

输出:

in first then
undefined

案例 2:使用 Promise()

getDocument(id)
.then(function (response) {
   console.log('in first then')
   return 'from two';
}).then(function (response) {
   console.log(response)
});

var getDocument=function(){
  return Promise.resolve('from getDocument');
}

输出:

in first then        
from two

问题

  1. 为什么会有输出差异?
  2. 我知道 Q.defer 是一种反模式,但是如何选择何时使用什么?

【问题讨论】:

  • 你能提供一个 plunkr/fiddle..吗?我怀疑第一个输出不应该有undefined 在第二个console.log
  • 哪个版本的 Q ... 因为 v1 工作正常
  • “我知道 Q.defer 是一种反模式,但是如何选择何时使用什么?” 使用 Promise 构造函数将非 Promise 异步操作包装在一个承诺。在使用 Promise 构造函数非常复杂或尴尬的情况下使用 .defer,而 .defer 会更优雅(这应该几乎永远不会)。
  • @JLRishe:你能举个例子解释一下吗
  • 你在用这个Q吗-github.com/kriskowal/q

标签: javascript node.js promise q jquery-deferred


【解决方案1】:

事实上,两个示例都返回相同的结果(相同的顺序)。检查此代码笔Example

var getDocument=function(){
  var b = Q.defer();
    b.resolve('Q from getDocument'); // here will do some async operation..this is just an example
  return b.promise;
}

getDocument(1)
.then(function (response) {
   console.log('Q in first then')
   return 'Q from two';
}).then(function (response) {
   console.log(response)
});

var getDocumentP=function(){
  return Promise.resolve('P from getDocument');
}

getDocumentP(1)
.then(function (response) {
   console.log('P in first then')
   return 'P from two';
}).then(function (response) {
   console.log(response)
});

2) 你可以在这里看到 Q.defer 的一些用法:Q.defer you´re doing it wrong

【讨论】:

  • The diffence happens because the promises one was built wrongly - 除了 Q 错了
  • 我看不出有什么问题...我知道如果您已经承诺返回,则不应使用延迟模式..但只是为了我的理解想知道为什么这两种方法给出不同的输出
  • 奇怪的事情。我正在 codepen 中测试您的代码,并且 Q 与 Promises 匹配:codepen.io/tuliofaria/pen/GrpqPE?editors=1111
  • 实际上我正在使用模块加载器(common js)来加载我的依赖项,例如 Q....当我直接在我的 HTML 页面上添加 Q 库的引用时,一切正常很好..但是当我通过模块加载器加载它时它不起作用。
猜你喜欢
  • 2015-04-25
  • 2018-03-12
  • 2016-12-07
  • 2019-01-20
  • 2020-04-17
  • 2017-05-17
相关资源
最近更新 更多