Waiting for AsyncStorage.getItem()

拜拜、爱过 提交于 2020-01-12 12:52:11

问题


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.

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?


回答1:


You can try either add a then after your getItem.

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

Or use await to wait the async operation to finish

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



回答2:


try this option and you will not get the

Syntax Error: Await is a reserved word

async getData() {
    return await AsyncStorage.getItem("@App:KEY");
}


来源:https://stackoverflow.com/questions/37120305/waiting-for-asyncstorage-getitem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!