【问题标题】:React Native AsyncStorage returns promise even used await and asyncReact Native AsyncStorage 甚至在使用 await 和 async 时也会返回 Promise
【发布时间】:2018-10-28 16:51:03
【问题描述】:

我研究了 AsyncStorage.getItem 中的问题。许多评论说我们应该在 AsyncStorage 上应用 awaitanync,例如

React Native AsyncStorage returns promise instead of value

AsyncStorage.getItem returning promise

但是,它仍然像下面的快照一样将 Promise 返回给我。在这个 Promise 中,_55 包含正确的用户信息。每个人都会帮助我找出问题并给我可能的解决方案吗?谢谢!

快照: Debugger snapshot

减速机:

import {AsyncStorage} from "react-native";
import {LOGIN, LOGOUT, UPDATE} from './../actions/authActions'
import user from "./index";

export type State = {
    user: Object,
    login: boolean,
}

getUser = async (string) => {  //Get user information form AsyncStorage
    try {
         return await AsyncStorage.getItem(string)
                  .then((user) => {
                     if (user !== null) {
                        return JSON.parse(user);
                     } else {
                        return null;
                   }
                });
    } catch (error) {
        return null;
    }
};

const initialState = {
    info: getUser(),
    login: !!this.info, // if not null, login = ture
};

function loginReducer(state: State = initialState, action) {
    switch (action.type) {
        case LOGIN:
            return {
                info: action.payload,
                login: true,
            };
        case LOGOUT:
            return {
                info: null,
                login: false,
            };
        case UPDATE:
            return {...state, info: Object.assign(state.info, action.payload)};
        default:
            return state;
    }
}   

行动:

import {AsyncStorage} from "react-native";
import {requestLogIn, requestLogOut} from "../../config/api/authApi"

export const LOGIN = "LOGIN";
export const LOGOUT = "LOGOUT";
export const UPDATE = "UPDATE";
export const ERROR = "ERROR";

export function login(user) {
    return dispatch => {
        return AsyncStorage.setItem("user", JSON.stringify(user)) //Store user information in AsyncStorage
            .then(() => {
                dispatch({
                    type: LOGIN,
                    payload: user
                })
            }).catch((error) => {
                console.warn("Error: ", error);
                dispatch({
                    type: ERROR,
                    payload: null
                })
            });
    }
}

export function logout(token) { //
    return dispatch => {
        return requestLogOut(token).then((status) => {
            if (status) {
                return AsyncStorage.removeItem("user")
                    .then(() => {
                        dispatch({
                            type: LOGOUT,
                        })
                    }).catch(() => {
                        dispatch({
                            type: ERROR,
                            payload: null
                        });
                    });
            } else {
                dispatch({
                    type: ERROR,
                    payload: null
                });
            }
        })

    }
} ..// other actions

【问题讨论】:

    标签: javascript react-native redux asyncstorage


    【解决方案1】:

    你的 getUser 是一个 async 函数,但你不是 awaiting 它:

    const initialState = {
        info: getUser(),      // <=== here
        login: !!this.info,
    };
    

    async 函数返回承诺。

    不要过多地进入更广泛的代码上下文,您可能想要做这样的事情:

    const initialState = {
        info: null,
        login: !!this.info,
    };
    getUser().then(info => initialState.info = info);
    

    或者类似的东西。请注意,这意味着在存储返回值之前,initialState.info 将是 null。如果您有更多需要该值的初始化,则必须从上面的 then 处理程序中触发它。

    (没有catch,因为你已经定义了getUser,所以它不能拒绝。)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-03-27
      • 1970-01-01
      • 2019-09-10
      • 2017-09-11
      • 2022-08-22
      • 2022-01-22
      相关资源
      最近更新 更多