Can anyone explain the use of $q service in angularjs?

I think the article I wrote about $q might help you.

Introduction to $q

$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.

This is a sample for creating a promise using $q

angular.module("app",[])
.controller("ctrl",function($scope,$q){
  var work = "resolve";
  var promise = $q(function(resolve, reject) {
    if (work === "resolve") {
        resolve('response 1!');
    } else {
        reject('Oops... something went wrong');
    }
  }); 
  promise.then(function(data) {
    alert(data)  

  }) 
})

$q.defer()

$q.defer() return the instance of the promise constructor. Once you create a defer object there are following methods and properties that you can access from that object

resolve(value) – resolves the derived promise with the value. If the value is a rejection constructed via $q.reject, the promise will be rejected instead.

reject(reason) – rejects the derived promise with the reason. This is equivalent to resolving it with a rejection constructed via $q.reject.

notify(value) - provides updates on the status of the promise's execution. This may be called multiple times before the promise is either resolved or rejected.

promise – {Promise} – promise object associated with this deferred

See the example

angular.module("app",[])
.controller("ctrl",function($scope,$q){
  var work = "resolve";

  function getData(){
    var obj = $q.defer();

    if (work === "resolve") {
        obj.resolve('response 1!');
    } else {
        obj.reject('Oops... something went wrong');
    }

    return obj.promise;
  } 
  getData().then(function(data) {
    alert(data)  

  }) 
})    

$q.all()

If a user need to send multiple request one shot,then the user can use $q.all() service.

 $q.all([$http.get('data1.json'),$http.get('data2.json')])
      .then(function(response){
        console.log(response[0].data) // data1.json response 
        console.log(response[1].data) // data1.json response 
 })

In here,there are two http request sent simultaneously to two separate JSON files to get data. The response comes as an array and response order is same as the HTTP request order.

$q.race()

$q.race() is very similar to $q.all(). But instead of sending response of each request, it will only return the one request response. Specifically, only return the response of first request that been executed. That does not mean it’s not going to send other requests. All the requests are sending but it's only return the response of the first request that executed.

 $q.race([$http.get('data1.json'),$http.get('data2.json')])
      .then(function(response){
        console.log(response[0].data) // return one response 
 })

In here response can be either data1.Json or data2.json. That's the downfall of using this method. Since its return the response of the first executed request, can’t be sure which request response will resolved by the promise. This method useful for bulk requests which you don’t want to see the response of all the requests

Conclusion

Use $q for constructing promises from non-promise Objects/callbacks, and utilize $q.all() and $q.race() to work with existing promises.


I like this question. Because, I too faced this.

This is a service that helps you run functions asynchronously, and use their return values when they are done processing.

Brief Description

Refer example

Promise with $q

Example :

app.service("githubService", function($http, $q) {

    var deferred = $q.defer();

    this.getAccount = function() {
        return $http.get('https://api.github.com/users/haroldrv')
            .then(function(response) {
                // promise is fulfilled
                deferred.resolve(response.data);
                // promise is returned
                return deferred.promise;
            }, function(response) {
                // the following line rejects the promise 
                deferred.reject(response);
                // promise is returned
                return deferred.promise;
            });
    };
});

Tags:

Angularjs