为什么我的redux-saga是异步的

时间:2016-10-06 20:26:15

标签: reactjs react-native redux redux-saga

在我的React-Native应用程序中,我编写了一个用户登录组件,用于向服务器发送用户名和哈希值,将哈希值与数据库中的哈希值进行比较并返回结果。我实现了using redux-saga

function* fetchUser(action) {
  try {
    const user = yield call(Api.fetchUser, action);
    yield put({type: types.USER_FETCH_SUCCEEDED, user});
  } catch (e) {
    yield put({type: types.USER_FETCH_FAILED, message: e.message});
  }
}

export function* watchFetchUser() {
  yield* takeEvery(types.USER_FETCH_REQUESTED, fetchUser);
}

export default function* rootSaga() {
  yield fork(watchFetchUser);
  // ...
}

我希望const user将包含来自API的响应,之后将运行yield put({type: types.USER_FETCH_SUCCEEDED, user})。但在yield call(Api.fetchUser, action) user undefined之后。但是Api.fetchUser会返回正确的回复。

我无法找到我的错误。在const user = yield call(Api.fetchUser, action)返回正确答案后,为什么undefined的结果为Api.fetchUser

fetchUser(action) {
    const url = `${apiUrls.LOGIN_URL}`;

    fetch(url, 'POST', action.user)
      .then(response => response.json())
      .then(res => res)
  }

1 个答案:

答案 0 :(得分:1)

您没有从fetchUser函数返回promise。它应该是

fetchUser(action) {
    const url = `${apiUrls.LOGIN_URL}`;

    return fetch(url, 'POST', action.user)
      .then(response => response.json())
      .then(res => res)
  }