In AngularJS, promises are handled using the $q
service. Promises are objects that represent the result of an asynchronous operation. They allow you to handle asynchronous operations in a more organized and readable manner. Here's how you can handle promises in AngularJS:
$q
service's defer()
method. This method returns an object with promise
, resolve
, and reject
properties.javascriptvar deferred = $q.defer();
javascript$http.get('/api/data')
.then(function(response) {
// Resolve the promise with the data
deferred.resolve(response.data);
})
.catch(function(error) {
// Reject the promise with an error
deferred.reject(error);
});
.then()
method. This method takes two callback functions as arguments - one for success (resolve
), and one for failure (reject
).javascriptdeferred.promise
.then(function(data) {
// Handle successful result
$scope.data = data;
})
.catch(function(error) {
// Handle error
console.error('Error occurred:', error);
});
.then()
methods. This allows you to execute asynchronous operations sequentially.javascript$http.get('/api/data1')
.then(function(response) {
// Process data1
return response.data;
})
.then(function(data1) {
// Use data1 to make another request
return $http.get('/api/data2');
})
.then(function(response) {
// Process data2
$scope.data = response.data;
})
.catch(function(error) {
// Handle any errors in the chain
console.error('Error occurred:', error);
});
This is a basic overview of handling promises in AngularJS using the $q
service. Promises are a fundamental concept in AngularJS for handling asynchronous operations and can greatly improve the readability and maintainability of your code.