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.60k
    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 = 'https://oyokeydev.s3.amazonaws.com/' + logo;
                deferred.resolve(logoFilePath);
            }).error(function(response) {
                console.log('Something went wrong');
                deferred.reject('Something went wrong');
            });
            return deferred.promise;
        }
    })

    $q.defer();

    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('http://appqa.oyokey.com:9080/api/v1/getdomainkeytag?apiKey=f92ecd00-d3ed-11e2-a6db-e9a269320bf6&domain=evontech.com');
        };
        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
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
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: