The $q
constructor function is used to create promises from asynchronous APIs that use callbacks to return results.
$q(function(resolve, reject) {...})
The constructor function receives a function that is invoked with two arguments, resolve
and reject
that are functions which are used to either resolve or reject the promise.
Example 1:
function $timeout(fn, delay) {
return = $q(function(resolve, reject) {
setTimeout(function() {
try {
let r = fn();
resolve(r);
}
catch (e) {
reject(e);
}
}, delay);
};
}
The above example creates a promise from the WindowTimers.setTimeout API. The AngularJS framework provides a more elaborate version of this function. For usage, see the AngularJS $timeout Service API Reference.
Example 2:
$scope.divide = function(a, b) {
return $q(function(resolve, reject) {
if (b===0) {
return reject("Cannot devide by 0")
} else {
return resolve(a/b);
}
});
}
The above code showing a promisified division function, it will return a promise with the result or reject with a reason if the calculation is impossible.
You can then call and use .then
$scope.divide(7, 2).then(function(result) {
// will return 3.5
}, function(err) {
// will not run
})
$scope.divide(2, 0).then(function(result) {
// will not run as the calculation will fail on a divide by 0
}, function(err) {
// will return the error string.
})