React Native AsyncStorage returns promise instead of value

前端 未结 2 1650
难免孤独
难免孤独 2021-02-09 05:20

I understand this is a very common problem in RN and I am still trying to understand the very possible advantage of returning a promise when loading data from a property file in

相关标签:
2条回答
  • 2021-02-09 06:12

    the thing is await turns the promise into a value, you don't need to use .then(). Try the following:

    const keys = await AsyncStorage.getAllKeys()
    const values = await AsyncStorage.multiGet(keys)
    
    // at this point `values` will have data for all keys 
    
    0 讨论(0)
  • 2021-02-09 06:14

    Once upon a time, i was having the same problem so what I did I will share with you here.

    Basically, your execution is moving forward without taking any value i.e undefined what you are getting right now so there are 3-4 ways to get out of this:

    1) async await 2) callback

    1) We will start with the callback which is use by most of the people.

    We will use your code to implement this:

        _getFilter(key,callback)
    {
        multiGet = (key) => {
            var collect;
            try {
              var value = AsyncStorage.multiGet(key).then(
                (values) => {
               //   value = values;
                  console.log('Then: ',values);
                 callback(values)
                });
            } catch (error) {
              console.log('Error: ',error);
            }
            console.log('Final: ',value);
    
            }
    }
    
        this._getFilter(key,function(filter){
          console.log('returned filter:',filter);
        });
    

    2)async/await

    If you are using await alone then you would get an error, to use await inside a function you have to declare the async function by setting async keyword before the function name.

     async _getFilter(key)
    {
    
    multiGet = async (key) => {
        var value,collect;
        try {
          value = await AsyncStorage.multiGet(key).then(
            (values) => {
              collect= values;
              console.log('Then: ',values);
            });
        } catch (error) {
          console.log('Error: ',error);
        }
        console.log('Final: ',value);
        return collect;
        }
    
    //calling the async function
    
    this._getFilter(key).then((filter)=>{
    if(filter!=null)
    console.log('returned filter:',filter)
    else
    console.log('error')
    })
    

    Hope this would clear your concepts and help you with other react native developers.I have seen lots of people struggling with this thing so today I got the chance to clear your doubts.

    Cheers :)

    0 讨论(0)
提交回复
热议问题