Redux Observable和异步提取调用

时间:2018-03-16 19:33:00

标签: rxjs rxjs5 redux-observable

我有像这样的史诗

const getProjectsEpic = action$ => 
  action$.ofType(state.GET_PROJECTS_REQUEST)
         .switchMap(action =>  fetchService())
         .map(res => actions.getProjectsRequestSuccess(res))
         .catch((error) => actions.getProjectsRequestFailure(error));

fetchService里面我得到了

export async function fetchService() {
  let response = await fetch('http://apiendpoint');
  return (validateStatusCode(response)) ? response.json() : new Error(response.statusText); 
}

试图找出我做错了什么,但控制台却在抛弃我:

runtime.js?c1c3:288 Uncaught (in promise) RangeError: Maximum call stack size exceeded
at Generator.invoke [as _invoke] (runtime.js?c1c3:288)
at Generator.prototype.(anonymous function) [as next] (webpack-internal:///../node_modules/regenerator-runtime/runtime.js:114:21)
at step (asyncToGenerator.js?6185:17)
at eval (asyncToGenerator.js?6185:35)

有人可以向我解释一下,以及如何在将来更好地调试类似的问题。

1 个答案:

答案 0 :(得分:1)

从这里learnRxJs - switchMap

项目函数应返回一个observable,因此我尝试包装fetchService函数的返回值。

import { of } from 'rxjs/observable/of';
...
export async function fetchService() {
  let response = await fetch('http://apiendpoint');
  return (validateStatusCode(response)) 
    ? of(response.json()) 
    : of(new Error(response.statusText)); 
}

或者也许

import { of } from 'rxjs/observable/of';
...
const getProjectsEpic = action$ => 
  action$.ofType(state.GET_PROJECTS_REQUEST)
         .switchMap(action => of(fetchService()))
         .map(res => actions.getProjectsRequestSuccess(res))
         .catch((error) => actions.getProjectsRequestFailure(error));