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

Ris*_*ari 6 javascript node.js promise jquery-deferred q

我试图理解为什么以下代码与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;
}
Run Code Online (Sandbox Code Playgroud)

输出:

in first then
undefined
Run Code Online (Sandbox Code Playgroud)

案例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');
}
Run Code Online (Sandbox Code Playgroud)

输出:

in first then        
from two
Run Code Online (Sandbox Code Playgroud)

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

Tul*_*ria 2

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

\n\n
var getDocument=function(){\n  var b = Q.defer();\n    b.resolve(\'Q from getDocument\'); // here will do some async operation..this is just an example\n  return b.promise;\n}\n\ngetDocument(1)\n.then(function (response) {\n   console.log(\'Q in first then\')\n   return \'Q from two\';\n}).then(function (response) {\n   console.log(response)\n});\n\nvar getDocumentP=function(){\n  return Promise.resolve(\'P from getDocument\');\n}\n\ngetDocumentP(1)\n.then(function (response) {\n   console.log(\'P in first then\')\n   return \'P from two\';\n}).then(function (response) {\n   console.log(response)\n});\n
Run Code Online (Sandbox Code Playgroud)\n\n

2) 你可以在这里看到 Q.defer 的一些用法:Q.defer you\xc2\xb4re 做错了

\n

  • “之所以会出现这种差异,是因为承诺的构建是错误的”——除了 Q 的承诺是错误的 (2认同)