Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Promises in Angular.JS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.36k
    Comment on it

    Promises in Angular.JS

    By using Promises we can execute a function asynchronously. we can use promises to specify what to do when a operation is success or failed. We have $q built in keyword in angular js for promises. let's create a example :

    .service('drawHomeCardService', function(apiCallFactory, $q) {
        this.getTheLogo = function() {
            var deferred = $q.defer();
            apiCallFactory.getData().success(function(response) {
                var logo         =  response[2].businessInfo.logoFilePath;
                var logoFilePath = '' + logo;
            }).error(function(response) {
                console.log('Something went wrong');
                deferred.reject('Something went wrong');
            return deferred.promise;


    here defer function create a object, by which there is a delay in result until a time.

    We call object from factory which is our apiCallFactory and we get the our image from api as below :

    .factory('apiCallFactory', function($http) {
        var apiCall = {};
        apiCall.getData = function() {
            return $http.get('');
        return apiCall;

    Now if our call is success in response then we get the image and we return deferred.resolve();. By deferred.resolve we determine whether a deferred object has been resolved and if our call is failed in response, control comes in error function where we return deferred.reject();

    Now in calling function, if response is success our first function which is in then is called and control comes here and on failed control comes in error function.

    drawHomeCardService.getTheLogo().then(function(logoFile) {
            $scope.logoFile = logoFile;
            console.log('After promise call logoFile==> ' + $scope.logoFile);
        }, function (error) {
            console.log("error " + error)


 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: