【问题标题】:Yield put fired before yield call finished在收益调用完成之前,收益看跌期权被触发
【发布时间】:2018-06-26 02:11:07
【问题描述】:

我尝试进行 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 在没有负载的情况下触发,但我可以在我的网络调试器中找到负载。

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

【问题讨论】:

    标签: javascript react-native redux redux-saga


    【解决方案1】:

    你忘了从函数checkOpenRegister返回Promise

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-03
      • 2012-08-15
      • 2019-09-19
      • 2015-10-11
      • 2011-01-13
      • 2015-11-15
      • 2018-08-15
      相关资源
      最近更新 更多