React Native AsyncStorage甚至使用await和async返回promise

时间:2018-05-18 09:25:54

标签: javascript react-native redux asyncstorage

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

React Native AsyncStorage returns promise instead of value

AsyncStorage.getItem returning promise

然而,它仍然像我下面的快照一样向我发回Promise。在此承诺中, _55 包含正确的用户信息。每个人都会帮我解决问题并给我可能的解决方案吗?谢谢!

快照: Debugger snapshot

减速器:

    package optimizer

    import (
        "github.com/tevino/abool"
        "errors"
        "sync"
        "runtime"
        "log"
    )

    type Optimizer struct {
        Handlers      []ofdHandler.Handler
    }

    func Make(handlers []ofdHandler.Handler, maxProcs int) Optimizer {
        runtime.GOMAXPROCS(maxProcs)
        return Optimizer{Handlers: handlers}
    }

    func (o Optimizer) Optimize(params operations.GetV1ReceiptsParams) (*models.Receipt, error) {
        var wg sync.WaitGroup
        wg.Add(len(o.Handlers))

        results := make(chan *models.Receipt)
        isCalculated := abool.NewBool(false)

        for _, handler := range o.Handlers {
            go func(handler ofdHandler.Handler) {
                log.Println("Starting handler: ", handler.GetName())
                defer wg.Done()

                if isCalculated.IsSet() {
                    log.Println("Result is calculated, exiting goroutine...")
                    return
                }

                receipt, err := handler.Handle(params)
                if err != nil {
                    log.Println(err)
                    return
                }

                if isCalculated.IsSet() {
                    log.Println("Result is calculated, exiting goroutine...")
                    return
                }

                log.Println("Writing result to channel...")
                isCalculated.Set()
                results <- receipt
            }(handler)
        }

        log.Println("Waiting...")
        wg.Wait()

        if receipt, ok := <-results; ok {
            return receipt, nil
        }

        return nil, errors.New("couldn't optimize with current list of Handlers")
    }

行动:

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;
    }
}   

1 个答案:

答案 0 :(得分:1)

您的getUserasync函数,但您不是await

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

async函数返回promises。

如果没有太多涉及代码的更广泛的上下文,你可能想要做这样的事情:

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

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

(没有catch,因为您已定义getUser,因此无法拒绝。)