所以我有这个代码将数据添加到每秒运行的数组:
var vehiclesT = asset.assetIDs;
if(!asset.assetIDs){
vehiclesT = [];
}
var y;
var vehicles = [];
for(y=0; y< vehiclesT.length; y++){
var url = 'api/assetName/?vid='+vehiclesT[y]+'&id='+id;
fetch(url, {credentials: 'include', method: 'get'}).then(function(body){
return body.text();
}).then(function(data) {
vehicles.push(data);
console.log(vehicles);
});
}
console.log(vehicles);
vehicles = vehicles.map(function(vehiclef, index){
return(
<li key={index}>{vehiclef}</li>
)
});
因此for循环中的日志会将一个数组打印到控制台,其中包含预期值。问题是,一旦for循环结束,车辆阵列由于某种原因被清除,所以第二个控制台日志打印出一个空数组,为什么这个以及如何阻止它?
谢谢,Ed。
答案 0 :(得分:1)
数组未被清除,因为javascript是异步的,你的第二个console.log会在循环执行之前先运行。
承诺/回调是解决此问题的最佳方式。
回电方式:
var vehiclesT = asset.assetIDs;
if(!asset.assetIDs){
vehiclesT = [];
}
var y;
var vehicles = [];
for(y=0; y< vehiclesT.length; y++){
var url = 'api/assetName/?vid='+vehiclesT[y]+'&id='+id;
fetch(url, {credentials: 'include', method: 'get'}).then(function(body){
return body.text();
}).then(function(data) {
vehicles.push(data);
console.log(vehicles);
if(y == vehiclesT.length - 1){
vehicles = vehicles.map(function(vehiclef, index){
return(
<li key={index}>{vehiclef}</li>
)
});
}
});
}