Q.defer()&的区别诺言()

时间:2017-01-09 04:33:51

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

我试图了解为什么以下代码与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是反模式但是如何选择何时使用什么?

1 个答案:

答案 0 :(得分:2)

实际上,两个示例都返回相同的结果(相同的顺序)。检查此codepen 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