javascript - Q.defer() 和 Promise() 的区别

标签 javascript node.js promise q jquery-deferred

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

Case 1 : When I'm using 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

Case 2: using 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

Question

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

最佳答案

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

关于javascript - Q.defer() 和 Promise() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41541082/

相关文章:

node.js - 将each与node-orm2一起使用的常规回调

php - 如何构建 PHP/Node 代理以在 https 网站上呈现外部 http 图像?

Javascript 三元运算符 : What is the condition in "(myvar) ?" when it is a number?

asp.net - 确保 Node.js 已安装并且可以在 PATH 目录之一中找到

javascript - ES6 和 lodash 中的 map 方法有什么区别?

javascript - 为什么 Promise 返回一个对象 Promise,即使我明确地输入 `return`?

javascript - 数据初始化 promise

javascript - 如何确保 promise 链返回一个对象

javascript - 向从特定数字开始的每个 x 列表添加边框

javascript - 有没有办法使用 Web Audio API 重新采样音频流?