0

All morning I've been trying to get the AsyncStorage.getItem to return the value of the actual item, not a promise.

Here's what I have that according to everything I've read should work:

export async function getToken(){

    try{
        var value = await AsyncStorage.getItem('authToken');
        return value;
    }catch (error){
        console.log(error);
    }

}   

I have tried chaining together many .thens, tried accessing the actual value field of the promise, but for some reason that returns a promise also. I've tried pretty much every suggestion on this site and it will always return a promise.

Chang Lib
  • 41
  • 5
  • It's just `AsyncStorage.getItem('credentials').then((result) => { console.log(result) })` result is your value. It's simply the `Promise.then(r => ... )` syntax. – G0dsquad Jun 07 '17 at 15:50
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Joe Clay Jun 07 '17 at 15:50
  • @G0dsquad Yes, I wish it were that easy, I've tried that many times and in many different formats and it still returns a promise. I think I may just look for a different storage system in react-native. – Chang Lib Jun 07 '17 at 15:56
  • Have you tried not awaiting it and removing it the `async` modifier? According to https://facebook.github.io/react-native/docs/asyncstorage.html your code above should work. Really odd! – G0dsquad Jun 07 '17 at 15:57
  • Even when I get the non async/await function to return something. It is always a promise even when returning from the .then part – Chang Lib Jun 07 '17 at 16:05
  • Hard to see from this above but it appears you set the inner value from storage and never assign it to the outer function return. Try setting a `let returnValue = ''` outside the try then assigning it as `returnValue = result`. You should then be able to return it beneath the try. – G0dsquad Jun 07 '17 at 16:06
  • 1
    I think I fixed it (for the time being) by making every single function that calls that getToken() function async and putting an await in front of every getToken call. extremely annoying but it works so it works. – Chang Lib Jun 07 '17 at 16:10

1 Answers1

0

Quoting the AsyncStorage documentation

... Each method in the API returns a Promise object.

and also based on this post, there is no way for you to access the value without the use of promise or any other async patterns (generators, callback etc).

You can use Realm as a storage without using promises. This is how you query data in realm (quoting the documentation):

let token = realm.objects('authToken'); // retrieves all authTokens
Mμ.
  • 8,382
  • 3
  • 26
  • 36