Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Constructing and using an AngularJS promise
angular.module('app', [])
.factory('FakeAmazonService', function($http, $q) {
return {
validateShippingAdddress: function(address) {
var deferred = $q.defer();
$http.post('/api/address/validate', address)
.then(function(resp) {
deferred.resolve({ success: true, data: resp});
}),
function(error) {
deferred.reject({ success: false, data: error});
});
return deferred.promise;
},
validateCreditCard : function(creditCard) {
var deferred = $q.defer();
$http.post('/api/creditCard/validate', creditCard)
.success(function(data) {
deferred.resolve({ isValid: data.success });
})
.error(function(error) {
deferred.reject({isValid: false, reason: error});
});
return deferred.promise;
},
placeOrder: function(order) {
var deferred = $q.defer();
$http.post('/api/order', order)
.success(function(data) {
deferred.resolve({success: true, msg: data});
})
.error(function(error) {
deferred.reject({success: false, msg: error});
});
return deferred.promise;
},
}
})
.controller('MainCtrl', function($scope, $q, FakeAmazonService, address, creditCard, order) {
var shippingPromise = FakeAmazonService.validateShippingAdddress(address);
var creditCardPromise = FakeAmazonService.validateCreditCard(creditCard);
var orderPromise = FakeAmazonService.placeOrder(order);
$q.all([creditCardPromise, shippingPromise, orderPromise]).then(function(responses) {
var creditCardMsg= responses[0];
var shippingMsg = responses[1];
var orderMsg = responses[2];
console.log('YAY!! Order Great Success!');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.