async componentDidMount(){
const resolvedCampgrounds = await this.returnThoseValues('getListings','/world')
resolvedCampgrounds.forEach(async feature=> {
if (feature['mapOn'].toUpperCase()==='TRUE'){
await coordinateData.push({
"key": feature['id'],
"Address": feature['street_address'] + feature['zip_code'],
"image": jpg,
"position": CodeAddress(feature['street_address'] + feature['zip_code'],this.props.google).then(value => {return value})
})
}
})
set_state(coordinateData);
CodeAddress()返回一个已解析的Promise,我试图通过.then()访问它的结果。到目前为止,我能够做到这一点的唯一方法是分别在每个对象的循环中调用set_state(而不是array.push-ing),但这还不够,因为我需要“批量推送”而不是每次都更改状态。
也许可以解决您原来的问题。
您需要添加另一个名为asyncForEach的方法,如下所示
async function asyncForEach(array, callback) {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
}
}
然后像这样更改您的代码
async componentDidMount(){ const resolvedCampgrounds = await this.returnThoseValues('getListings','/world') asyncForEach(resolvedCampgrounds, async feature=> { if (feature['mapOn'].toUpperCase()==='TRUE'){ const position = await CodeAddress(feature['street_address'] + feature['zip_code'],this.props.google); coordinateData.push({ "key": feature['id'], "Address": feature['street_address'] + feature['zip_code'], "image": jpg, "position": position }) } }) set_state(coordinateData);
了解更多here