-1

I am not able to understand the use of $q service in angular js. Can some one please give elaboration on this topic that

what is the $q service in angularjs? How can we use that

Sheetal
  • 29
  • 3

1 Answers1

1

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

Introduction to $q

$q is an angular define a service. It’s 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 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

Conclusion

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

Tejinder Singh
  • 1,070
  • 2
  • 8
  • 24