I try to understand what angular $q does but I just do not get it.
When and how should you use $q in angular?
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)
$q is promise service in angular it is used to make promise while making Async Server Call for some data.As we don't know how much time it will take to bring data from a server so we take a promise to notify us when we get data and to do something(call some function) when data is received.
Promise is used when you want to get data from a server Async(without affecting other things on page=>Hang of Event Loop).
Refer These links
https://thinkster.io/a-better-way-to-learn-angularjs/promises