我想我误解了async await是如何工作的,特别是对于来自另一个文件的函数。
import { getAddressFromLongLat } from "../hooks/queries-hook";
import React, { useEffect, useState } from "react";
const Component = (props) => {
const [address, setAddress] = useState(null);
useEffect(() => {
const fetchFromLongLat = async () => {
if (props.coords) {
const response = await getAddressFromLongLat(props.coords);
console.log("response from nominatim " + JSON.stringify(response, null, 4));
setAddress(response);
}
};
fetchFromLongLat();
}, []);
return <></>;
};
然后输入queries-hook.js
import axios from "axios";
export const getAddressFromLongLat = async (coords) => {
const URL = "http://nominatim.openstreetmap.org/reverse";
const response = await axios.get(URL, {
params: {
format: "json",
lat: coords.lat,
lon: coords.long
},
headers: {
"Content-Type": "application/json; charset=UTF-8"
}
});
return {
street: response.address.road + " " + response.address.house_number,
cp: response.address.postcode,
city: response.address.town,
country: response.address.country_code.toUpperCase()
};
};
有人能解释我应该如何写正确的代码与那些异步等待没有错误:
可能的未处理承诺拒绝(标识:0):类型错误:undefined不是对象(评估'response.address. road')
3条答案
按热度按时间gcuhipw91#
问题是由于
response
不包含address
属性和所有其他属性。但response.data
包含。你必须在
return
之前添加一个console.log(response);
来解决这个问题。{ "lat": 50.806002951249546, "long": 4.410705976188183 }
的输出将是这样的:所以固定功能:
e5nqia272#
第一个
pdsfdshx3#
我不确定,但也许你不需要在第二个函数中使用async... wait。这就像tako中的tako。但你只需要在一个tako钟中使用两个tako。