我想使用axios将地址转换为它们各自的坐标。
这是我的尝试,但由于它是异步的,因此无法使用。
let array = [];
axios.get('https://www.data.qld.gov.au/api/3/action/datastore_search?resource_id=346d58fc-b7c1-
4c38-bf4d-c9d5fb43ce7b')
.then((response) => {
const records = response.data.result.records;
records.forEach((record) => {
axios.get('https://maps.googleapis.com/maps/api/geocode/json', {
params: {
address: record.address,
key: GOOGLE_KEY,
}
}).then(response => {
record.response.coordinate;
array.push(record);
});
});
我在想,是否可以根据RESPONSE对象的长度进行n次((响应))?
答案 0 :(得分:1)
您可以利用Promise.all获得所需的结果。
(async () => {
const {
data: {
result: { records }
}
} = await axios.get(
"https://www.data.qld.gov.au/api/3/action/datastore_search?resource_id=346d58fc-b7c1-4c38-bf4d-c9d5fb43ce7b"
);
const coordinates = await Promise.all(
records.map(async (record) => {
const response = await axios.get(
"https://maps.googleapis.com/maps/api/geocode/json",
{
params: {
address: record.address,
key: GOOGLE_KEY
}
}
);
return response.coordinate;
})
);
})();