Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

react native - Waiting for 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...