React Native AsyncStorage返回promise而不是value [英] React Native AsyncStorage returns promise instead of value

查看:72
本文介绍了React Native AsyncStorage返回promise而不是value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这是RN中一个非常常见的问题,我仍在尝试理解从属性文件加载数据时返回promise的非常可能的优势,而不仅仅是返回值,这使得链接请求非常麻烦。 。但无论如何。以下是我现在所拥有的,它是AsyncStorage RN实现的包装器:

  multiGet = async(key)=> ; {
var value = null;
try {
value = await AsyncStorage.multiGet(key).then(
(values)=> {
value = values;
console.log('然后:',值);
});
} catch(错误){
console.log('错误:',错误);
}
console.log('Final:',value);
返回值;
}

此时,值未定义。在我的主要代码中,我有这个:

  var filter = this._getFilter(); 
console.log('返回过滤器:',过滤器);

_getFilter函数是使用AsyncStorage包装器的函数,但'返回的过滤器'是在第一个之前记录的函数,所以它不会在继续之前等待返回的值,所以我得到一个未定义的值。



起初,我认为只需使用async / await AsyncStorage wold就会返回一个值而不是一个promise但是在测试之后,我得到的值是:

  value = await AsyncStorage.getItem('key')

仍然是一个承诺,所以我必须使用then()来读取值。



基本上我在日志中看到的订单是:

  _getFilter 
返回值:undefined
然后:value:这里我从键中得到正确的值,但是代码已经通过了,我在变量
中没有正确的值

我不知道发生了什么或如何正确处理这个问题。这应该是非常简单和常见的用例。



我很乐意在不使用第三方模块的情况下解决这个问题。



谢谢



解决方案
编辑:了解更多关于async / await和callbacks的概念,我终于有一个有效的代码。我不喜欢它,因为它使代码很难阅读。我可能需要重构它以使用promises但是现在,它可以工作。以下是一些片段,以防有人发现同样的问题:

  this._getFilter(body,this._filterSearchCallback,callback); 

注意:我正在通过链发送正文,因为我在通过时完成信息功能。第二个参数是实际进行获取查询的第一个回调,第三个回调是获取函数的返回。

  _getFilter (body,callback,returnCallback){

{...}

this._sh.multiGet(keysBanks).then(
(banks)=> {
filter.banks = banks;
console.log(银行);
this._sh.multiGet(keysCards).then(
(cards)=> {
console.log(cards);
filter.credit_cards = cards;
callback(body,filter,returnCallback);
});
}
);

}

这里基本上我链了几个得到因为我需要来自商店的几个价值观。这是我不喜欢的部分。 _sh是我的StorageHelper,它是AsyncStorage的包装器,没什么特别的。

  multiGet = async(key)=> {
const value = await AsyncStorage.multiGet(key);
返回值;
}

然后我的最后一个回调实际上进行了获取并发送了JSON响应本机反应中的主屏幕:

  _filterSearchCallback(正文,过滤,回调){

正文。 filter = filter;

return fetch(apiUrl,{method:'post',body:JSON.stringify(body)})
.then((response)=> response.json())
.then((responseJson)=> {
callback(responseJson);
})
.catch((error)=> {
console.error(错误);
回调(responseJson);
});
}

我会改进这个并使其更清洁但是现在,它有效。希望它也能帮助别人。

解决方案

曾几何时,我遇到了同样的问题所以我做了什么,我将在这里与你分享。



基本上,你的执行正在向前推进而没有任何价值,即未定义你现在得到的是什么,所以有3-4种方法可以摆脱这个:



1)异步等待
2)回调



1)我们将从大多数使用的回调开始我们将使用您的代码实现此目的:

  _getFilter(key,callback)
{
multiGet =(key)=> {
var collect;
try {
var value = AsyncStorage.multiGet(key).then(
(values)=> {
// value = values;
console.log ('然后:',值);
回调(值)
});
} catch(错误){
console.log('错误:',错误);
}
console.log('Final:',value);

}
}

this._getFilter(键,函数(过滤器){
console.log('返回过滤器:',过滤器);
});

2)async / await



如果你正在使用await然后你会得到一个错误,在函数内使用await你必须通过在函数名之前设置async关键字来声明异步函数。

  async _getFilter(key)
{

multiGet = async(key)=> {
var value,collect;
try {
value = await AsyncStorage.multiGet(key).then(
(values)=> {
collect = values;
console.log('然后:',值);
});
} catch(错误){
console.log('错误:',错误);
}
console.log('Final:',value);
返回收款;
}

//调用异步函数

this._getFilter(key).then((filter)=> {
if(filter != null)
console.log('返回过滤器:',过滤器)
else
console.log('error')
})

希望这会清除你的概念,并帮助你与其他反应原生的开发者。我看到很多人都在努力解决这个问题所以今天我有机会清除你的怀疑。



干杯:)


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 instead of just returning the value, which makes chaining requests very cumbersome...but anyway. Here is what I have right now, which is a wrapper from the AsyncStorage RN implementation:

multiGet = async (key) => {
    var value = null;
    try {
      value = await AsyncStorage.multiGet(key).then(
        (values) => {
          value = values;
          console.log('Then: ',values);
        });
    } catch (error) {
      console.log('Error: ',error);
    }
    console.log('Final: ',value);
    return value;
    }

At this point, value gets undefined. In my main code I have this:

var filter = this._getFilter();
console.log('returned filter:',filter);

The _getFilter function is the one using the AsyncStorage wrapper but the 'returned filter' is logging before the first function so it is not waiting for the returned values before continue, so I get an undefined value.

At first, I thought that just by using the async/await the AsyncStorage wold return a value instead of a promise but after testing, the value I get from:

value = await AsyncStorage.getItem('key') 

is STILL a promise, so I have to use then() to read the value.

Basically the order that I am seeing in the logs is:

_getFilter
returned value: undefined
Then: value: here I get the correct value from the keys but the code already passed and I don't have the correct value in the variable

I have no clue what is going on or how to handle this correctly. This is supposed to be very simple and common use case.

I would love to solve this without using a third party module.

Thanks

SOLUTION Edit: After understanding a little more about the concepts of async/await and callbacks, I finally have a code that works. I don't like it, because it makes the code very hard to read. I might need to refactor it to use promises but for now, it works. Here are some snippets in case someone finds the same issue:

this._getFilter(body,this._filterSearchCallback,callback);

Note: I am sending the body through the chain because I am "completing" the information as I pass the functions. The second parameter is the first callback that actually makes a fetch query and the third callback is the return of the fetch function.

_getFilter(body,callback,returnCallback){

      {...}

      this._sh.multiGet(keysBanks).then(
        (banks) => {
          filter.banks = banks;
          console.log(banks);
          this._sh.multiGet(keysCards).then(
            (cards) => {
              console.log(cards);
              filter.credit_cards = cards;
              callback(body,filter,returnCallback);
            });
        }
      );

    }

Here basically I am chaining a couple of gets because I need several values from the store. This is the part I dont really like. _sh is my StorageHelper which is a wrapper to the AsyncStorage, nothing fancy.

multiGet = async (key) => {
    const value = await AsyncStorage.multiGet(key);
    return value;
    }

Then my very last callback that actually makes the fetch and send the JSON response to the main screen in react native:

_filterSearchCallback(body,filter,callback){

      body.filter = filter;

      return fetch(apiUrl, {method: 'post', body: JSON.stringify(body)})
      .then((response) => response.json())
      .then((responseJson) => {
        callback(responseJson);
      })
      .catch((error) => {
        console.error(error);
        callback(responseJson);
      });
    }

I will improve this and make it cleaner but for now, it works. Hope it helps others too.

解决方案

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 :)

这篇关于React Native AsyncStorage返回promise而不是value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆