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
$q. defer() allows you to create a promise object which you might want to return to the function that called your login function.
$q is an angular defined service. It's the same as new Promise(). But $q takes things to the next level by enhancing additional feature that developers can use to perform complex tasks more simply. resolve(value) – resolves the derived promise with the value.
Deferred is complete, one of the fastest and natural promise implementation in JavaScript, with Deferred you can write clear maintainable code that takes maximum out of asynchronicity, in fact due to multi-dimensional nature of promises (chaining and nesting) you're forced to program declaratively.
The Promise object supports two properties: state and result. While a Promise object is "pending" (working), the result is undefined. When a Promise object is "fulfilled", the result is a value. When a Promise object is "rejected", the result is an error object.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With