2016-12-25 89 views
2

我一直堅持這個angularjs/javascript的異步執行。請幫助同步循環內的承諾?

注意

虛擬API用於樣品的目的。

那些虛擬API實際上是一個真正的AnugularJS服務。

我使用XmlHttpRequest進行演示,因此不需要爭論第三個參數是錯誤還是真實的。

問題

在for循環中,calculateFormulaValue函數被調用,並根據參數,它會調用一些API,並得到承諾的對象值。但是for循環在promise對象返回之前完成,並且我無法將最終對象保存在rowCollection中。

我們如何重構下面的代碼來獲得所需的結果?

代碼在這裏 - >https://jsbin.com/xocisivuro/edit?js,console

CODE

var rowCollection = []; 
var headerCollection = ["Formula 1", "Formula 2", "Formula 3", "Formula 4", "Formula 5", "Formula 6", "Formula 7"]; 
var currentFormulaValues = {}; 
//var finalCollection = 
function generate(){ 

    for(var i=0;i<headerCollection.length;i++){ 

     calculateFormulaValue(i,headerCollection[i]); 
     console.log("current index" +i + " -->" +headerCollection[i]); 


    } 
} 

function calculateFormulaValue(j,currentFormula){ 

    //Some common code which need to run .. 

    if(currentFormula == "Formula 1"){ 
     var promise = new Promise(function(resolve, reject) { 
     var request = new XMLHttpRequest(); 

     request.open('GET', 'https://api.icndb.com/jokes/random'); 
     request.onload = function() { 
      if (request.status == 200) { 
      resolve(request.response); 
      } else { 

      reject(Error(request.statusText)); 
      } 
     }; 

     request.onerror = function() {reject(Error('Error fetching data.')); 
     }; 

     request.send(); 
     }); 

     promise.then(function(data) { 

     currentFormulaValues[currentFormula] = JSON.parse(data).value.id; 
     //rowCollection[j] = JSON.parse(data).value.id; 

     console.log("j - " + j +" ->" + (JSON.stringify(currentFormulaValues))); 
     }, function(error) { 
     console.log('Promise rejected.'); 
     }); 
    } 

    else if(currentFormula == "Formula 2"){ 
     var promise = new Promise(function(resolve, reject) { 
     var request = new XMLHttpRequest(); 

     request.open('GET', 'https://api.icndb.com/jokes/random'); 
     request.onload = function() { 
      if (request.status == 200) { 
      resolve(request.response); 
      } else { 

      reject(Error(request.statusText)); 
      } 
     }; 

     request.onerror = function() {reject(Error('Error fetching data.')); 
     }; 

     request.send(); 
     }); 

     promise.then(function(data) { 
     currentFormulaValues[currentFormula] = JSON.parse(data).value.id; 
     //rowCollection[j] = JSON.parse(data).value.id; 
     console.log("j - " + j +" ->" + (JSON.stringify(currentFormulaValues))); 

     }, function(error) { 
     console.log('Promise rejected.'); 
     }); 
    } 

    // for all other formulas 

    else{ 
     var promise = new Promise(function(resolve, reject) { 
     var request = new XMLHttpRequest(); 

     request.open('GET', 'https://api.icndb.com/jokes/random'); 
     request.onload = function() { 
      if (request.status == 200) { 
      resolve(request.response); 
      } else { 

      reject(Error(request.statusText)); 
      } 
     }; 

     request.onerror = function() {reject(Error('Error fetching data.')); 
     }; 

     request.send(); 
     }); 

     promise.then(function(data) { 

     currentFormulaValues[currentFormula] = JSON.parse(data).value.id; 
     //rowCollection[j] = JSON.parse(data).value.id; 
     console.log("j - " + j +" ->" + (JSON.stringify(currentFormulaValues))); 

     }, function(error) { 
     console.log('Promise rejected.'); 
     }); 

    } 

    if(j == headerCollection.length-1){ 
     console.log("SAVE FINAL") 
     rowCollection.push(currentFormulaValues); 
     console.log(JSON.stringify(currentFormulaValues)) 
     } 
} 

電流輸出

"current index0 -->Formula 1" 
"current index1 -->Formula 2" 
"current index2 -->Formula 3" 
"current index3 -->Formula 4" 
"current index4 -->Formula 5" 
"current index5 -->Formula 6" 
"SAVE FINAL" 
"{}" 
"current index6 -->Formula 7" 
"j - 0 ->{\"Formula 1\":98}" 
"j - 1 ->{\"Formula 1\":98,\"Formula 2\":175}" 
"j - 2 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523}" 
"j - 3 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523,\"Formula 4\":399}" 
"j - 4 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523,\"Formula 4\":399,\"Formula 5\":119}" 
"j - 5 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523,\"Formula 4\":399,\"Formula 5\":119,\"Formula 6\":261}" 
"j - 6 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523,\"Formula 4\":399,\"Formula 5\":119,\"Formula 6\":261,\"Formula 7\":164}" 

預期輸出

"current index0 -->Formula 1" 
"j - 0 ->{\"Formula 1\":98}" 

"current index1 -->Formula 2" 
"j - 1 ->{\"Formula 1\":98,\"Formula 2\":175}" 

"current index2 -->Formula 3" 
"j - 2 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523}" 

"current index3 -->Formula 4" 
"j - 3 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523,\"Formula 4\":399}" 

"current index4 -->Formula 5" 
"j - 4 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523,\"Formula 4\":399,\"Formula 5\":119}" 

"current index5 -->Formula 6" 
"j - 5 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523,\"Formula 4\":399,\"Formula 5\":119,\"Formula 6\":261}" 

"current index6 -->Formula 7" 
"j - 6 ->{\"Formula 1\":98,\"Formula 2\":175,\"Formula 3\":523,\"Formula 4\":399,\"Formula 5\":119,\"Formula 6\":261,\"Formula 7\":164}" 


//if j == headerCollection.length-1, then.. 

"SAVE FINAL" // then do ... rowCollection.push(currentFormulaValues); 

任何幫助實現預期輸出將是很好的。提前致謝。

回答

3

你可以返回您創建calculateFormulaValue的承諾,通過將return的關鍵字:

return promise.then(function(data) { // ... etc 

在這裏你有這樣的結構,以確保該函數總是返回的承諾所有的地方做這個(甚至更好:嘗試重用每個公式通用的代碼 - 你有很多代碼重複)。

然後你的主循環可以建立一個新的數組,每個元素都是返回的承諾:

var promises = headerCollection.map(function (collection, i) { 
    console.log("current index" +i); 
    // return(!) the promise you get from each call. This will become 
    // an element in a new array, returned by *map*. 
    return calculateFormulaValue(i, collection); 
}); 

現在你可以等待所有承諾,與Promise.all完成:

Promise.all(promises).then(function() { 
    // now your object is available. 
}); 

NB:您應該進一步改進您的代碼以避免使用全局變量,例如結果對象currentFormulaValues

+0

完美。感謝您的短而脆的提示和筆記。 工作小提琴[鏈接](https://jsbin.com/pucumemumo/edit?js,console) – Zing14