【发布时间】: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
问题
- 为什么会有输出差异?
- 我知道 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