简体   繁体   English

AsyncStorage返回不正确的值

[英]AsyncStorage returns incorrect value

I am very new with react native and might be doing this completely wrong. 我对本机反应非常陌生,可能做的完全错误。 As suggested on react native documentation, i am using a wrapper for my AsyncStorage. 正如对本机文档的建议,我正在为我的AsyncStorage使用包装器。 What I am Doing: 我在做什么:

  1. I have a class named Storage which serves as wrapper to AsyncStorage code: 我有一个名为Storage的类,可作为AsyncStorage代码的包装器:

     'use strict'; var React = require('react-native'); var { AsyncStorage } =React; module.exports={ store(key,value) { AsyncStorage.setItem(key,value); }, get(key) { return AsyncStorage.getItem(key); }, } 
  2. Another class Auth looks for a value with key auth (which is saved already) code: 另一类Auth使用密钥auth(已保存)代码查找值:

     'use strict'; var React = require('react-native'); var Storage=require('./Storage'); module.exports={ authKeyExists() { console.log("IntelliSpend: In Auth::authKeyExists"); var authKeyPromise=Storage.get('auth'); var keyExists=true; authKeyPromise.then((authKey)=>{ console.log('Authkey:'+authKey); if(authKey){ console.log('Authkey exists'); keyExists= true; } else { console.log('Authkey does not exists'); keyExists= false; } }).done(); return keyExists; } } 

Ideally as value with key 'auth' exists so it should print "Authkey exists" and should return keyExists as true. 理想情况下,存在具有键“ auth”的值,因此它应打印“ Authkey exist”并应将keyExists返回为true。 But it happens opposite. 但这恰恰相反。

On Further diagnosys i found that function authKeyExists returns well before code inside promise objects executes. 在进一步的诊断中,我发现在promise对象内部的代码执行之前,函数authKeyExists返回的很好。

I have seen several examples but they all use AsyncStorage on the Screen component itself (i tried that too and failed). 我已经看到了几个示例,但是它们都在Screen组件本身上使用了AsyncStorage(我也尝试过并且失败了)。 I want to abstract out AsyncStorage by using my storage class. 我想通过使用我的存储类来抽象出AsyncStorage。 Please let me know where i am mistaking. 请让我知道我在哪里。

Your function authKeyExists() will always return true... The functions inside a promise run asynchronously and will actually fire after return keyExists so none of the logic in there that sets keyExists will have any effect. 您的函数authKeyExists()将始终返回true ... promise中的函数将异步运行,并且在返回keyExists后实际上将触发,因此设置keyExists的逻辑都不起作用。 If you want to use the values from the promise you need to use a callback: 如果要使用promise中的值,则需要使用回调:

authKeyExists(callback)
{
  var keyExists;
  var authKeyPromise=Storage.get('auth');
  authKeyPromise.then((authKey)=>{

      if(authKey){
        keyExists= true;
      }
      else {
        keyExists= false;
      }

      callback(keyExists);

  }).done();      
}    

Which you can then use like this: 然后,您可以像这样使用它:

Auth.authKeyExists( (keyExists)=> {

   // do something with keyExists

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM