等待 AsyncStorage.getItem() [英] Waiting for AsyncStorage.getItem()

查看:25
本文介绍了等待 AsyncStorage.getItem()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 React Native 应用程序中使用 AsyncStorage 来存储有关用户的信息.getItem() 函数是异步的,当我想从存储系统加载数据时需要我实现一个回调.

I am using AsyncStorage in my React Native application to store information about the user. The getItem() function is asynchronous and requires me to implement a callback when I want to load data from the storage system.

AsyncStorage.getItem("phoneNumber").then((value) => {
    this.setState({"phoneNumber": value});
}).done();

因为从存储中检索一个值不需要很长时间,所以我想等到操作完成再继续执行.

Because retrieving a value from the storage does not take long, I would like to wait until the operation is complete before continuing execution.

是否可以以非异步的方式加载数据?如果没有,是否有一种简单的方法可以让我等到 getItem() 调用完成后再继续执行?

Is it possible to load data in a way that is not Asynchronous? If not, is there an easy way for me to wait until the getItem() call is complete to continue executing?

推荐答案

您可以尝试在 getItem 之后添加 then.

You can try either add a then after your getItem.

AsyncStorage.getItem("phoneNumber").then((value) => {
    this.setState({"phoneNumber": value});
})
.then(res => {
    //do something else
});

或者使用await等待async操作完成

Or use await to wait the async operation to finish

var value = await AsyncStorage.getItem(STORAGE_KEY);
//use value to do something else.

这篇关于等待 AsyncStorage.getItem()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆