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

Async helper functions with AsyncStorage in React Native

我想做的是提醒本地存储中的 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>
    );
  }

}

以下代码有效,但我希望能够从辅助函数内部完成。如果你在顶部看到,我有 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;
    });
}

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

我知道我显然没有正确处理它的整个异步性质,所以如果有人有任何指导,我将不胜感激。我仍然不了解如何在 React Native 中使用异步函数。

这是因为当您调用函数时 pouchDB_helper.pouchDB_config() 它 returns 一个承诺。

有多种方法可以利用这一优势。

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

export async function pouchDB_config() {
  return await AsyncStorage.getItem('company_id');
}

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

pouchDB_config().then((company_id) => {
  console.log(company_id);
});

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

const otherAsyncFunction = async () => {
  const company_id = await pouchDB_config();
  console.log(company_id);
}