gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 05:31:55 25 4
gpt4 key购买 nike

我试图理解为什么以下代码与 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com