Promise然后array.push另一个诺言不起作用? [重复]

问题描述 投票:-1回答:1
我正在尝试遍历从API异步返回的值的数组,并且在该循环中,我想调用另一个返回诺言的函数。我无法在循环中获得第二个承诺。我该怎么做?

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),但这还不够,因为我需要“批量推送”而不是每次都更改状态。
javascript promise
1个回答
0
投票
代码中的一个问题是您正在使用forEach来做一些异步的事情,而forEach不支持它。

也许可以解决您原来的问题。

您需要添加另一个名为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
© www.soinside.com 2019 - 2024. All rights reserved.