是否可以使用 Promise 进行 object
迭代?
这是我的源代码。
Object.keys(drop).map((key) => {
RNGooglePlaces.lookUpPlaceByID(drop[key].placeID)
.then((results) => {
results.t = results.address;
results.l = `${results.latitude},${results.longitude}`;
array.push(results);
})
.catch((error) => reject(error));
});
console.log(JSON.stringify(array));
上面的代码不起作用,因为我在 object.keys.map
函数中使用了 Promise。
为了获得正确的数组结果,我想我必须使用 Promise for Object.map
我已经使用 PromiseArrays 进行 Promise 迭代,但它不起作用。
有没有最好的解决办法?
最佳答案
注意,return
没有值编辑自.map()
和console.log(array)
在 Promise
之外调用链。您可以使用Promise.all()
并从 .map()
返回一个值获得一组已满足的 Promise
对象位于 .then()
let promises = Promise.all(
Object.keys(drop).map(key =>
RNGooglePlaces.lookUpPlaceByID(drop[key].placeID)
.then(results => {
results.t = results.address;
results.l = `${results.latitude},${results.longitude}`;
return results;
})
)
);
promises.then(results => console.log(results))
.catch(error => console.error(error));
关于javascript - 对对象使用 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46598782/