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: 
What you want is to chain promises. You could do it like so:

```
//Just so we have a promise to start with for the chain.
let promiseMerchantKey = Promose.resolve();
for(let count = 0; count < 10; count++){

// random select category from list

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

// create merchant
// check if merchant exists before add
promiseMerchantKey = randomMerchantName.then((marchantName)=>{
    return new Promise((resolve, reject) => {
        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);
                    }
                });
              });
});

// all other promises to insert record into different child

}

```
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
        }
    });
}

```