Javascript for循环不等待所有承诺执行

时间:2017-07-25 06:26:58

标签: javascript for-loop asynchronous react-native

我遇到了异步调用和for循环的问题。我现在面临的是for循环永远不会等待所有承诺在执行另一轮之前完成。我的代码框架如下:

 // removed code 

有没有办法做到这一点,for循环会在执行另一轮之前等待我执行的所有承诺?

3 个答案:

答案 0 :(得分:0)

您也可以在自称为自我的函数中执行此操作:

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

使用promises的更好方法是then运算符。 这将是一个语法:

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

答案 1 :(得分:0)

你想要的是连结承诺。你可以这样做:

//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

}

答案 2 :(得分:-1)

我在这里写了一个原型,希望有帮助:

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

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