我试图了解为什么以下代码与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
问题
答案 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