React Native AsyncStorage getItem使用异常,求正确调用方法
Hey there! That strange {"40":0,"_65":0,"_55":null,"_72":null} value you're getting is actually a mis-handled Promise object. The issue comes from mixing async/await and callback-style handling in your getItem call—AsyncStorage's getItem behaves differently depending on whether you pass a callback or not. Let me walk you through the correct ways to use it:
First: Make sure you're using the right package
In modern React Native, the core AsyncStorage has been moved to a separate package. So first, ensure you've installed and imported it correctly:
import AsyncStorage from '@react-native-async-storage/async-storage';
Correct Approach 1: Use async/await (Recommended)
This is the cleanest and most readable way. Skip the callback entirely, use await to wait for the Promise to resolve, and wrap everything in a try/catch to handle errors:
async function addSessionId() { try { // Wait for getItem to resolve and get the actual value const sessionId = await AsyncStorage.getItem("session_id"); console.warn(sessionId); return sessionId; } catch (error) { // Handle any errors (e.g., storage access issues) console.error('Failed to fetch session_id:', error); return null; // Or return a default value of your choice } }
Correct Approach 2: Use Promise .then()/.catch()
If you prefer callback-style chaining instead of async/await, you can use the Promise-based API directly (no need for async/await here):
function addSessionId() { return AsyncStorage.getItem("session_id") .then(sessionId => { console.warn(sessionId); return sessionId; }) .catch(error => { console.error('Failed to fetch session_id:', error); return null; }); }
Why your original code didn't work
When you pass a callback to getItem, the method doesn't return a Promise—it executes the callback with the result instead. But you tried to await this non-Promise return value, which wraps it in a resolved Promise, and you ended up seeing the internal state of that Promise object instead of your actual session_id.
How to call the function
No matter which approach you use, when you call addSessionId, you'll need to handle its async nature:
// Using async/await async function useSession() { const id = await addSessionId(); // Do something with id here } // Or using .then() addSessionId().then(id => { // Do something with id here });
内容的提问来源于stack exchange,提问作者yogesh

