【发布时间】:2019-11-03 04:40:46
【问题描述】:
我正在学习 React 中的 RxJS/Redux-Observable。
但我有一个关于return Promise 的问题。
不使用 RxJS/Redux-Observable
这样我就可以将承诺返回给组件,让它可以使用.then() 进行下一步操作
在 React 的行动中
export const getData = () => (dispatch) => {
try {
const dataResponse = await dataAPI.getData();
dispatch(getDataAction(dataResponse));
return Promise.resolve(dataResponse);
} catch (error) {
return Promise.reject(error);
}
}
在 React 的组件中
componentDidMount = () => {
const {
getData
} = this.props;
getData().then(function(response) {
// I can use this response action for some UX Action.
})
}
使用 RxJS/Redux-Observable
我不知道如何回报承诺
在 React 的史诗行动中
export const getDataEpic = (action$, state$) => {
return action$.pipe(
ofType(FETCH_DATA),
mergeMap(action => {
let _response = ajax.getJSON(dataAPI.getData());
return _response.pipe(
delay(3000),
map(response => {
return fetchDataFulfilledAction(response);
}),
takeUntil(action$.pipe(
filter(
action => action.type === CANCEL_FETCH_DATA
)
))
)
})
);
}
在 React 的组件中
componentDidMount = () => {
const {
getData
} = this.props;
getData().then(function(response) {
// How to get this response result ?
})
}
我知道使用Reducer是一种处理方式,但我仍然想知道如何返回promise。
谢谢大家
【问题讨论】:
-
你可以使用
toPromise()将Observable变成Promise -
@Martin 嗨,我在 rxjs 官方文档用法中找不到 toPromise()?您介意提供更多使用参考或代码笔示例吗?非常感谢
-
恐怕没有例子,但这是
Obseravable类rxjs.dev/api/index/class/Observable#toPromise上的方法
标签: javascript reactjs rxjs redux-observable