Question: I was having some problem with asynchronous call and for loop. What I am facing now is the for loop never waits for all the promise to complete before execute another round. My code skeleton as such:

```
 // removed code 

```

Is there any way to do this such that the for loop will wait for all my promises done executing before executing another round?

Answer: 
You can also do it in a function that calls it self:

```
function ramdomMerch (index, maxIndex) {
  count = index;
  count++;
  if (count > maxIndex) {
    exit(); //This will end the loop as soon as it hits the maxIndex
  }

  // random select merchant
  let randomMerchantName = new Promise((resolve, reject) => {
      merchantName = branchlist[branchIndex].merchantName;
      resolve(merchantName);
  });

            let promiseMerchantKey = new Promise((resolve, reject) => {
              randomMerchantName.then((merchantName) => {
                firebase.database().ref('merchants').orderByChild('merchantName').equalTo(merchantName).once('value', function(snapshot) {
                  var merchantData = snapshot.val();
                    if (merchantData){
                      console.log('merchant exists');
                      snapshot.forEach(function(childSnapshot) {
                        var item = childSnapshot.val();
                        item.key = childSnapshot.key;
                        resolve(item.key);
                      });
                    }else{
                      var merchantKey = firebase.database().ref('merchants').push({
                        merchantName : merchantName
                      }).getKey();

                      resolve(merchantKey);
                    }
                    ramdomMerch(count, maxIndex); // Here we simply call after finish the next "loop"
                });
              });
            });
}

randomMerch(1, 10); //We start it like an loop with the start and endIndex

```

A better way to work with promises is the [then](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) operator.
It would be a syntax like:

```
let promiseMerchantKey = new Promise(( ... 
promiseMerchantKey.then(function(value) {
   // Sucess, call next promise or next loop if it was the last
  }, function(reason) {
  // error
});

```
I write a prototype here, hope that help:

```
var donePromise = 0;
let n = 10;
for(let count = 0; count < n; count++){
    DoAPromisse(function() {
        donePromise++;

        if (donePromise == n) {
            //all promisesses done
        }
    });
}

```