Q.defer()和Promise()之间的区别

我试图理解为什么下面的代码与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是一个反模式,但接下来如何select什么时候使用?

实际上,两个例子都返回相同的结果(相同的顺序)。 检查这个codepen 示例

 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你做错了