Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and how use angular $q?

Tags:

angularjs

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

When and how should you use $q in angular?

like image 847
Sven van den Boogaart Avatar asked Apr 21 '26 05:04

Sven van den Boogaart


2 Answers

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;
}
like image 80
Gabriel Martinez Bustos Avatar answered Apr 24 '26 00:04

Gabriel Martinez Bustos


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)

like image 39
Mike Moore Avatar answered Apr 24 '26 00:04

Mike Moore



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!