javascript - 如何在 React 中使用 Rxjs 返回 Promise?

标签 javascript reactjs rxjs redux-observable

我正在学习 React 中的 RxJS/Redux-Observable。

但是我有一个关于return Promise的问题。

不使用 RxJS/Redux-Observable

这样我就可以将 promise 返回给组件,让它可以使用 .then() 进行下一步操作

在 React 的 Action 中

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

我不知道如何返回 promise

在 React 的史诗 Action 中

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 。

谢谢大家

最佳答案

所以当我们返回一个 promise 时你犯了一个典型的错误你不应该为成功或错误返回一个新的 promise 而是返回两个函数:

resolve -> 为了成功将它与 then 链接起来 reject -> 因为 faileure 将它与 catch 链接起来了!

希望这段代码能帮到你,如果你需要澄清,请告诉我

export const getData = () => (dispatch) => new Promise((resolve, reject) => {
    const dataResponse = await dataAPI.getData();
    dispatch(getDataAction(dataResponse))

    if(dataResponse.status === '200') {
      return resolve(dataResponse) }
    else {
     return reject(dataResponse.error)
  }   
})

关于javascript - 如何在 React 中使用 Rxjs 返回 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56684635/

相关文章:

reactjs - 仅更改 React 中选定的选择下拉列表的值

javascript - 在 RxJS 中是否有更简洁(更动态)的方式来编写此映射函数?

Angular 5 ngrx 效果没有导出成员 'ofType'

javascript - registration.showNotification 不是函数

angular - Angular 的 ExceptionHandler 可观察到的错误处理

javascript - 如果满足条件可以清除setInterval吗?不使用 componentDidMount?

javascript - 如何下载带有文件名的文件?

javascript - 带有 z-index 的流体布局

javascript - 如何将可见绑定(bind)与单选按钮可观察参数一起使用?

javascript - React - 箭头函数与 bind() 和带参数的事件