代码之家  ›  专栏  ›  技术社区  ›  Soufiaane

“redux saga”无法异步工作

  •  2
  • Soufiaane  · 技术社区  · 8 年前

    这是我正在使用的代码:

    import {AUTH_REQUEST} from '../constants/authentication';
    import {authSuccess, authError} from '../actions/login';
    import {takeEvery, call, put, fork, all} from 'redux-saga/effects';
    import axios from 'axios';
    
    const authenticate = (username, password) => {
        axios
            .post('http://localhost:8000/api/auth/login/', {username, password})
            .then((response) => {
                console.log('RESPONSE: ', response.data);
                return response.data;
            })
            .catch((error) => {
                throw error;
            });
    };
    
    function* watchAuthRequest({username, password, resolve, reject}) {
        try {
            const result = yield call(authenticate, username, password);
            console.log('RESULT', result);
            yield put(authSuccess(result));
            yield call(resolve);
        } catch (error) {
            yield put(authError(error));
            yield call(reject, {serverError: 'Something bad happend !'});
        }
    }
    
    const authSaga = function* authSaga() {
        yield takeEvery(AUTH_REQUEST, watchAuthRequest);
    };
    
    export default function* rootSaga() {
        yield all([
            fork(authSaga),
        ]);
    };
    

    当我提交表单(我使用的是redux表单)时,这就是我进入控制台日志的原因:

    RESULT: undefined
    RESPONSE:  Object {user: Object, token: "04a06266803c826ac3af3ffb65e0762ce909b07b2373c83b5a25f24611675e00"}
    

    甚至 authSuccess result )

    我做错什么了吗?

    1 回复  |  直到 8 年前
        1
  •  4
  •   rvidal    8 年前

    你错过了一个 return :

    const authenticate = (username, password) => {
        return axios
            .post('http://localhost:8000/api/auth/login/', {username, password})
            .then((response) => {
                console.log('RESPONSE: ', response.data);
                return response.data;
            })
            .catch((error) => {
                throw error;
            });
    };