Skip to content Skip to sidebar Skip to footer

Asynchronus Calls In Angularjs

I am new to Javascript and Angularjs. I wanted to know , how to call a function asynchronously without waiting for it to return from it. Please let me know and if there is some exa

Solution 1:

Use Angular's deferred:

functionmyAsyncFunction() {
    var deferred = $q.defer();

    //..setTimeout(function() {
        deferred.resolve({ message: "resolved!" });
        // or deferred.reject({ message: "something went terribly wrong!!" });
    }, 1000);
    //..return deferred.promise;
}

myAsyncFunction()
    .then(function(data){
        // successconsole.log("success", data.message);
    }, function(data) {
        // failconsole.log("error", data.message);
    }).finally(function() {
        // always
    });

Solution 2:

You can use a deferred to return a promise, you can then resolve the promise once your function is complete. Try something like this:

http://jsfiddle.net/adcoxwga/

var myApp = angular.module('myApp',[])

.service('myService', function($q, $timeout){

    this.someFunction = function(){
        var deferred = $q.defer(); //making a new deferred$timeout(function(){
            deferred.resolve('something'); //resolving the deferred with a response
        }, 3000);

        return deferred.promise; //returning a promise
    }

})

.controller('MyCtrl', function($scope, myService){

    myService.someFunction().then(function(response){ //calling the asynchronous function
       console.log(response); //getting response
    }, function(error){
        console.log(error); //getting error
    });

});

Solution 3:

You have a couple of different options ahead of you, but one thing to note is that you have to use a callback or promise for asynchronous activity. Since you are using angular, I'd suggest using promise's.

Using a promise

If you are writing an http call to an api, you can use either $http or $resource. If you start to research angular providers, you will see that $http returns a promise, while $resource returns a promise but you must call it specifically to access it. For instance:

someService

function someServiceFunction () {
  return $http.get('some/url');
}

someController

$scope.results = [];
someService.someServiceFunction().then(function(data) {
    $scope.results = data;
});

Something to note is that the first returned function is the success scenario and if you declare a second callback, then it is the failure scenario.

If you were to use callbacks in the same scenario:

Using a callback

someService

functionsomeServiceFunction (callback) {
  return$http.get('some/url')
           .success(callback);
}

someController

$scope.results = [];
someService.someServiceFunction(function(data, status, headers, config) {
    $scope.results = data;
});

Here's a link to the $http provider. Here's a link to the $resource provider.

Cheers!

Post a Comment for "Asynchronus Calls In Angularjs"