$q Class
Creates and manages promises. Used by $http and $routing.
$q is used to create a deferred object, which contains a promise. The deferred is used to create and manage promises.
A promise accepts resolution, rejection and notification handlers that are executed when the promise itself is resolved, rejected or notified. The handlers are attached to the promise via the .then() method.
You can attach multiple handlers by calling .then() multiple times with different handlers. In addition, you can chain .then() calls. In this case, the return value from .then() is a new promise that's attached to the resolve handler passed to .then(). This way you can return promises from your resolve handler and the next .then() will wait until that promise is resolved to continue. Usually used to do multiple asyncronous calls in sequence.
Constructor
Methods
all
-
promises
Takes an array of promises (called inner promises) and creates a new promise (called outer promise) that resolves when all the inner promises resolve. If any of the inner promises are rejected, the outer promise is immediately rejected as well and any other inner promises left over are discarded.
E.g. if you have three inner promises, A, B, and C, then the outer promise O is resolved once all three A, B and C are resolved.
If A is resolved, and B is rejected, and C is pending, then O will be rejected regardless of C's outcome.
Parameters:
-
promises
ArrayArray of promises
Returns:
Example:
let greeting = $q.defer();
let name = $q.defer();
$q.all([greeting.promise, name.promise])
.then((greeting, name) => console.log(greeting + ' ' + name));
greeting.resolve('Welcome');
name.resolve('John')
//=> "Welcome John"
defer
()
Deferred
Create a new defer. This method requires no arguments, the returned defer has the methods required to resolve/reject/notify the promise.
Returns:
Example:
let defer = $q.defer();
defer.promise.then((name) => console.log('Hi ' + name));
defer.resolve('John');
//=> "Hi John"
when
-
value
-
[onResolve]
-
[onReject]
-
[onNotify]
Creates a new promise and resolves it with value
. If value
is a promise,
the returned promise is attached to value
. If onResolve, onReject or
onNotify are given, they are attached to the new promise.
Parameters:
-
value
| PromiseValue that the returned promise is resolve with. If value is a promise, the returned promise is attached to value.
-
[onResolve]
Function optionalResolve handler
-
[onReject]
Function optionalRejection handler
-
[onNotify]
Function optionalNotification handler
Returns:
Example:
$q.when('John').then((name) => console.log('Hi ' + name));
//=> "Hi John"