Monday, 6 June 2016

Promises 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.