Question: In angularjs I am trying to execute services one after the other in a sequential manner. Below is my code,

```
$q.when()  
    .then(function () { 
            console.log("Start"); 
            return getMyDetailsService.MyDetails();                     
        })  
    .then(function (MyDetails) {
            console.log("Step 2"); 
            var AllTabs = [];               
            angular.forEach(MyDetails, function(value, key){                
                AllTabs.push({ "TabName":value.checkfile });                
            });             
        return AllTabs;         
        })  
    .then(function (AllTabs) {
            console.log("Step 3"); 
                angular.forEach(AllTabs, function(value, key){
                    console.log(value.TabName);
                    return getMongodbDataService.MongoDatadb(value.TabName)
                    //console.log(MongoDatadb)
                })      
        })
    .then(function (MongoDatadb) { console.log("Step 4"); console.log(MongoDatadb); })
    .then(function (AllTabs) { console.log("Finish"); }) 

```

The problem is, i am getting "undefined" after "Step 4" in console. It seems the service "getMongodbDataService" not taking the input properly. If i comment forEach loop and execute with hard code input, it works. 

```
//angular.forEach(AllTabs, function(value, key){
      //console.log(value.TabName);
      return getMongodbDataService.MongoDatadb('Tab01')
      //console.log(MongoDatadb)
//})

```

Please suggest , where i am making mistake in promises handling. Please also tell me if service returns multiple "MongoDatadb" responses, will the next function (Step 4 one) process all request or will take only the last one. As per my need, i have to process all the response one by one. 

Many Thanks

Answer: 
[`angular.forEach`](https://docs.angularjs.org/api/ng/function/angular.forEach) will not return any value on "Step 3". 
You should use [`map()`](https://developer.mozilla.org/uk/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to return an array of promises and [`$q.all()`](https://docs.angularjs.org/api/ng/service/$q#all) to combine them all into a single promise that will be resolved when all of the input promises are resolved:

```
return $q.all(AllTabs.map(function(tab){ return getMongodbDataService.MongoDatadb(tab.TabName) }));

```
It because you return command is in the scope of 'foreach' method not in the scope of your promise treatment.