I try to understand what angular $q does but I just do not get it.
When and how should you use $q in angular?
You can use $q to create promises, first, you need create a instance of $q and then create the promise, and finally return this promise like this;
function init(){
test().then(x=>console.log(x))
.catch(x=>console.log(x));
}
function test(){
var defered = $q.defer();
var promise = defered.promise;
$timeout(()=>{
defered.resolve("Resolve");
//defered.reject("Reject");
},100);
return promise;
}
In previous experience, $q is useful when using angular, as you are, so that you can return deferred objects that can allow for nice promise syntax such as
function myFunc () {
var deferred = '.defer();
// do something
if (thingSucceeded) {
$q.resolve('success');
} else {
$q.reject('failure');
}
return deferred;
}
myFunc().then(function () {
// handle success
}).catch(function () {
// handle failure
});
Basically, if you need to provide the then and catch promise-style chaining in this example, a promise library such as $q can be used. There are other promise/deferred implementations available. For example, if you can use es6, you can just use the new/native Promise (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
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