Reputation: 1051
I'm trying to understand why following code is behaving differently with Q.defer() and 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;
}
Output:
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');
}
Output:
in first then
from two
Question
Upvotes: 6
Views: 7171
Reputation: 904
In fact, both examples are returning the same result (the same order). Check this 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) You can see here some uses of Q.defer: Q.defer you´re doing it wrong
Upvotes: 2