【问题标题】:How to return Promise using Rxjs in React?如何在 React 中使用 Rxjs 返回 Promise?
【发布时间】: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()?您介意提供更多使用参考或代码笔示例吗?非常感谢
  • 恐怕没有例子,但这是Obseravablerxjs.dev/api/index/class/Observable#toPromise上的方法

标签: javascript reactjs rxjs redux-observable


【解决方案1】:

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

resolve -> 用于将其与 then 链接的成功 拒绝 -> 用 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)
  }   
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-03
    • 2020-03-07
    • 2023-03-11
    • 1970-01-01
    • 2022-12-22
    • 1970-01-01
    • 2019-08-19
    • 2021-04-03
    相关资源
    最近更新 更多