Thursday 18 June 2015

Wait for all async call to finish, which is invoked inside a for loop then execute the next sync statement in Angular JS.

In this post we are going to see how to make a wait for all async call to finish which is invoked inside a for loop , then continue the Next statement to execute. Let we take a one scenario. 

1.  we got a list of employees id in array, we have a service where we can get the employee record but we can pass only one employee id, 
2. so there is a necessity we have to loop all employees to make a each call for every employee, 
3.  Another condition is there after fetching all employees records we have to pass that array to the another call where all      employees records saved in DB to get department id.

Now we have one block here that every call inside the for loop is async, so it will execute the next condition save logic with out wait for all async call finish, Now how we can avoid that situation.

Let we make Promises to do that for us, save all request inside a array and pass it to the $q.all, then wait in the Callback to finish all , and continue the Next statement to execute.


var app = angular.module('app', []);


app.factory('DBfactory', ['$http', function ($http) {
    return {
        getEmployee: getEmployee,
        addEmployeesToDeptarment: addEmployeesToDeptarment
    };

    function getEmployee(empid) {
        return $http({
            url: '/service/getemployee',
            method: 'get',
            data: {
                id: empid
            },
            cache: true
        });
    }

    function addEmployeesToDeptarment(employees) {
        return $http({
            url: '/service/postEmployees',
            method: 'Post',
            data: {
                emp: employees
            }
        });
    }

}]);



app.controller('appContrl', function ($scope, $q, DBfactory) {

    $scope.getData = function (employees) {

        var departmentID = '';
        var EmployeesRecords = [];
        var promises = [];

        for (var k = 0; k < employees.length; k++) {
           
            /* Asyn call for every emp id to get the Employee records */
            promises.push(DBfactory.getEmployee(employees[i]).then(function (result) {
                EmployeesRecords.push(result.data.value);
            }));

        }

        $q.all(promises).then(function () {
        
       /* Now Promises wait for all Async call then executes this callback */
       /* Code Runs inside this will be execute only all async oalls of for loop finishes */
            
          DBfactory.addEmployeesToDeptarment(EmployeesRecords).then(function (result) {

                var res = result.data.value || (result.data || []);
                departmentID = res.DepartmentID;

            });

        })

    }

});




From this post you can learn how to execute all async calls in for loop and wait for all to finish to execute the next sequence statement in angular js.