我必须更改对象的属性并保留所有其他属性。在更改之后,我需要将对象推入数组。但是,由于异步问题(这是我的猜测),推送的值仍然是初始对象。我该如何解决这个问题?这是我的代码:
layer.features.forEach(function(feature){
var geometry = feature.geometry;
var igeometry = geometry.transform("EPSG:4326");
feature.geometry = igeometry;
myFeature.push(feature);
});
在代码中,推入myFeature []的功能始终是几何体的初始特征,而不是igeometry的新特征。
答案 0 :(得分:0)
您应该尝试登录控制台几何体,igeometry,功能并确保它们都是您期望的值。从查看你的代码它应该工作。所以举个例子。 https://repl.it/INoA
let arr = [{a: 1}, {a:2}, {a:3}, {a:4}];
function wait(item) {
return new Promise (resolve => {
item.a = item.a + 1;
setTimeout(resolve, 100, item);
});
}
let newArr = arr.map(item => {
return wait(item);
});
Promise.all(newArr).then(values => {
console.log(values);
});
您的承诺有几种选择。您可以在promise中解析它,也可以使用新的await方法来执行相同的操作。
http.get('someGetAddres').then(result => {
var myFeature = [];
layer.features.forEach(function(feature){
var geometry = feature.geometry;
var igeometry = geometry.transform("EPSG:4326");
feature.geometry = igeometry;
myFeature.push(feature);
});
});
async function getFeature() {
var layer = await http.get('myWebsite');
var myFeature = [];
layer.features.forEach(function(feature){
var geometry = feature.geometry;
var igeometry = geometry.transform("EPSG:4326");
feature.geometry = igeometry;
myFeature.push(feature);
});
}