在 React Native 中使用 AsyncStorage 的异步辅助函数

bry*_*yan 2 javascript reactjs react-native react-native-ios

我想要做的是提醒company_id本地存储中的那个。

import React, { Component } from 'react';
import { ActivityIndicator, AsyncStorage, Button, StatusBar, Text, StyleSheet, View, } from 'react-native';
import * as pouchDB_helper from '../utils/pouchdb';

type Props = {};
export default class HomeScreen extends Component<Props> {

  render() {

    AsyncStorage.getItem('company_id', (err, result) => {
      alert(result);
    });

    return (
      <View style={styles.container}>
        <Button title="Hi" onPress={this.doSomething} />
      </View>
    );
  }

}
Run Code Online (Sandbox Code Playgroud)

以下代码有效,但我希望能够从辅助函数内部执行此操作。如果你在顶部看到,我有import * as pouchDB_helper from '../utils/pouchdb';

在那里我有以下内容:

import React from 'react';
import { AsyncStorage } from 'react-native';
import PouchDB from 'pouchdb-react-native'


export async function pouchDB_config() {
  return AsyncStorage.getItem('company_id', (err, result) => {
      return result;
    });
}
Run Code Online (Sandbox Code Playgroud)

而不是AsyncStorage.getItem()代码,如果我这样做,alert(pouchDB_helper.pouchDB_config())我会得到一个具有以下内容的对象:{"_40":0,"_65":0,"_55"_null,"72":null}

我知道我显然没有对所有的异步性质做正确的事情,所以如果有人有任何指导,我将不胜感激。我仍然不知道如何在 React Native 中使用异步函数。

szn*_*brt 5

这是因为当您调用该函数时,pouchDB_helper.pouchDB_config()它会返回一个承诺。

有不同的方法可以利用这一点。

在您的 util/pouchdb 中,将函数更改如下:

export async function pouchDB_config() {
  return await AsyncStorage.getItem('company_id');
}
Run Code Online (Sandbox Code Playgroud)

现在您可以按如下方式调用此函数:

pouchDB_config().then((company_id) => {
  console.log(company_id);
});
Run Code Online (Sandbox Code Playgroud)

或者您可以在异步函数中的任何其他地方调用它:

const otherAsyncFunction = async () => {
  const company_id = await pouchDB_config();
  console.log(company_id);
}
Run Code Online (Sandbox Code Playgroud)