React native: async, await, fetch



在我的应用程序中,我想执行一个HTTP请求,等待请求完成,并显示结果

function HomeScreen({ navigation, route }) {
....
console.log("Try to decode");
const result = GeocodingUtils.getAdressFromCoordinates(myLocation);
console.log("Get Address OK");
<Text>{result}</Text>

这是getAdressFromCoordinates方法

export default class GeocodingUtils {
static async getAdressFromCoordinates(location) {
try {
const response = await fetch("valid_url");
const responseJson = await response.json();
.....
console.log(street + " " + streetNumber);
return street + " " + streetNumber;
} catch (error) {
console.log(error);
}
}

我告诉他们控制台的输出应该是这样的:

尝试解码

。玛丽街

Get Address OK

但这是真实的输出:

尝试解码

Get Address OK

/打印承诺对象/

所以我有两个问题:

第一个是我的geocode函数应该"停止"代码流执行直到其结束第二个是我想在Text组件

中打印函数的结果提前通知

您遇到的问题是,您正在调用异步方法,而不是在将其存储在结果const中之前等待它的响应。

这就是为什么你会得到一个承诺。

try this:

let result;
GeocodingUtils.getAdressFromCoordinates(myLocation).then(r => result = r);

或者将函数定义为async:

var HomeScreen = async({ navigation, route }) => {
....
console.log("Try to decode");
const result = await GeocodingUtils.getAdressFromCoordinates(myLocation);
console.log("Get Address OK");
<Text>{result}</Text>

我找到的解决方案是使用useEffect钩子,就像
kevinSpaceyIsKeyserSöze所说的。

useEffect(() => {
(async () => {
....
let addressString = await GeocodingUtils.getAdressFromCoordinates(
latitude, longitude
);
})();
}, []);

您需要awaitGeocodingUtils.getAdressFromCoordinates的结果:

function HomeScreen({ navigation, route }) {
....
console.log("Try to decode");
const result = await GeocodingUtils.getAdressFromCoordinates(myLocation);
console.log("Get Address OK");
<Text>{result}</Text>

你也可以使用promises:

function HomeScreen({ navigation, route }) {
....
console.log("Try to decode");
GeocodingUtils.getAdressFromCoordinates(myLocation).then(function(result){
console.log("Get Address OK")
<Text>{result}</Text>
})

最新更新