Yield 在 yield 调用完成之前被解雇

Yield put fired before yield call finished

我尝试进行 API 调用,但是在 yield 调用完成执行之前 yield put 被触发。这是我的代码:

Api.js

function callApi(endpoint, token = null) {
  const fullUrl =
    endpoint.indexOf(API_ROOT) === -1 ? API_ROOT + endpoint : endpoint;

  return axios
    .get(fullUrl, { headers: { Authorization: token } })
    .then(resp => {
      return Object.assign([], resp.data);
    })
    .catch(error => ({ error: error.message || "Something bad happened" }));
}

export const checkOpenRegister = (branchId, userId, token) => {
  console.log("in check open");
  callApi(
    `Branches/${branchId}/registers?filter[where][status]=1&filter[where][userId]=${userId}`,
    token
  );
};

在我的传奇中 index.js

function* doCheckAuthInfo() {
  try {
    const user = yield select(getUser);

    if (user.token) {
      yield put({
        type: CHECK_AUTH_INFO_SUCCEED,
        payload: { token: user.token }
      });
      yield put({ type: CHECK_OPEN_REGISTER_REQUESTED });
    } else {
      //redirect to login
      yield put(NavigationActions.navigate({ routeName: "Login" }));
    }
  } catch (error) {
    yield put({ type: CHECK_AUTH_INFO_FAILED, error });
  }
}

function* doCheckOpenRegister() {
  try {
    const user = yield select(getUser);

    const response = yield call(
      checkOpenRegister,
      user.branchId,
      user.userId,
      user.token
    );
    yield put({ type: CHECK_OPEN_REGISTER_SUCCEED, payload: response });
  } catch (error) {
    yield put({ type: CHECK_OPEN_REGISTER_FAILED, error: error.message });
  }
}

function* watchCheckAuthInfo() {
  yield takeLatest(CHECK_AUTH_INFO_REQUESTED, doCheckAuthInfo);
}

function* watchCheckOpenRegister() {
  yield takeLatest(CHECK_OPEN_REGISTER_REQUESTED, doCheckOpenRegister);
}

// use them in parallel
export default function* rootSaga() {
  yield all([
    fork(watchCheckAuthInfo),
    fork(watchCheckOpenRegister)
  ]);
}

在我的故事中,在函数 doCheckOpenRegister 上,yield PUT 在没有负载的情况下触发,但我可以在我的网络调试器中找到负载。

我需要负载来触发重定向操作。在这种情况下,当有响应值时,我需要重定向到主页。

你忘记了 return 来自函数的 Promise checkOpenRegister

export const checkOpenRegister = (branchId, userId, token) => {
  console.log("in check open");
  return callApi(
    `Branches/${branchId}/registers?filter[where][status]=1&filter[where][userId]=${userId}`,
    token
  );
};