3

I try to understand what angular $q does but I just do not get it.

When and how should you use $q in angular?

Sven van den Boogaart
  • 11,833
  • 21
  • 86
  • 169
  • Are you asking on why to use Promises in general, or in which case `$q` is better than some more modern library, like bluebird, or the native Promises? – Patrick J. S. Jun 04 '16 at 22:29
  • 2
    Possible duplicate of [AngularJS : Where to use promises?](http://stackoverflow.com/questions/15604196/angularjs-where-to-use-promises) – James P Jun 04 '16 at 22:37
  • @PatrickJ.S. I dont understand the consept of $q, for which situations should you use it? I get it has something to do with async loading but when should you use $q as in, in which situatinon? I use $http to get stuff from an api. – Sven van den Boogaart Jun 04 '16 at 22:45
  • Sometimes it's just best to know that it;s there even if you aren't sure how to use it right now and when the time comes that you really need it a lightbulb will go off and you know it is there – charlietfl Jun 04 '16 at 23:55
  • 1
    One very useful part is `$q.all()` which you may find use for before other parts of library...allows array of promises ( like multiple $http) to resolve before code runs after all are completed – charlietfl Jun 04 '16 at 23:59

3 Answers3

2

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;
}
1

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)

Mike Moore
  • 7,228
  • 10
  • 42
  • 63
  • The "do something" might be using the `$http` service, as you are, and then you would have an opportunity to do something else, such as validation or restructure data, etc. Then, you can still return a deferred object. You might not need to! – Mike Moore Jun 04 '16 at 22:49
  • 1
    Comment is an anti-pattern since `$http` returns a promise itself. Not a good example – charlietfl Jun 04 '16 at 23:52
  • How is it an anti-pattern to do something with a promise-based service and then do something else with a promise? For example, handle the resolve or reject of the `$http` and then decide whether to resolve or reject and do it with `$q`? – Mike Moore Jun 05 '16 at 00:11
  • 2
    https://github.com/petkaantonov/bluebird/wiki/Promise-anti-patterns First one fits what you are mentioning in comment – charlietfl Jun 05 '16 at 00:12
  • Honestly I think my example wasn't really detailed enough to garner being called an anti-pattern, but the reference you shared is great and hopefully helpful to the OP – Mike Moore Jun 05 '16 at 00:16
  • 1
    Not code or text in answer.... I meant in your first comment after answer... *The "do something" might be using the $http*. That's where people commonly use the anti pattern in referenced link doing `$http.get().then(resp){ return $q.resolve()})` – charlietfl Jun 05 '16 at 00:16
  • OK, but "do something" could still be some asynchronous thing, that doesn't implement the promise API, right? – Mike Moore Jun 05 '16 at 00:28
  • 1
    Absolutely .. like a third party async call that doesn't return a promise – charlietfl Jun 05 '16 at 00:30
  • 1
    In fact a third part async call like google maps geodocde api or even `navigator.geolocation` would be good examples for when to use `$q` – charlietfl Jun 05 '16 at 00:32
  • @charlietfl So i should not use it with $http? Lets say i have a factory that does an api call and a controller that calls that factory method, – Sven van den Boogaart Jun 06 '16 at 23:32
  • @SvenB no...not for single `$http` call...it already returns a promise and you can use `then` on that promise – charlietfl Jun 06 '16 at 23:33
0

$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

https://thinkster.io/http

Aniket Jha
  • 1,751
  • 11
  • 13