首页 > 解决方案 > 发生错误时尝试连接到 redux-saga 中的套接字

问题描述

我使用以下渠道准备了 saga:

function* createEventChannel(socket, dataItem) {
  const stompClient = Stomp.over(socket);
  const token = yield select(makeSelectToken);
  return eventChannel(emit => {
    stompClient.connect(
      getAuthorization(token),
      frame => {
        stompClient.subscribe('/queue/data', message => {
          const response = JSON.parse(message.body);
          emit(response);
        });
        stompClient.subscribe('/queue/error', message => {
          const error = JSON.parse(message.body);
          emit(error);
        });
        stompClient.send(
          '/register',
          {},
          JSON.stringify({
            request: {
              type: dataItem,
            },
          })
        );
      },
      error => emit({ error: 'Lost connection' })
    );
    return () => {
      socket.close();
      console.log('return close: ');
    };
  });
}

export function* initializeChannel(
  actionNames,
  requestParam
) {
  const mySocket = new SockJS('/ws');
  const channel = yield call(createEventChannel, mySocket, requestParam);
  while (true) {
    const { unmount, response } = yield race({
      unmount: take(UNMNOUT),
      response: take(channel),
    });
    if (unmount) {
      channel.close();
    } else {
      if (response) {
        yield put({
          type: FETCH_SUCCESS,
          payload: response.data,
        });
      }
      if (response.error) {
        yield put({
          type: actionNames.FETCH_ERROR,
          payload: response.error,
        });
      }
    }
  }
}

我知道这是一段相当长的代码,但这就是我设法准备的。现在我面临三个问题:

标签: javascriptreactjsreduxwebsocketredux-saga

解决方案


推荐阅读