我一直堅持這個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);
任何幫助實現預期輸出將是很好的。提前致謝。
完美。感謝您的短而脆的提示和筆記。 工作小提琴[鏈接](https://jsbin.com/pucumemumo/edit?js,console) – Zing14