简体   繁体   English

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

[英]How to return Promise using Rxjs in React?

I am learning RxJS/Redux-Observable in React. 我正在React中学习RxJS / Redux-Observable。

But I have a question about return Promise . 但是我有一个关于return Promise的问题。

Without using RxJS/Redux-Observable 不使用RxJS / Redux-Observable

so that I can return promise to component let it can use .then() for next action 这样我就可以将诺言返回给组件,使其可以使用.then()进行下一步操作

In the Action of React 在反应行动中

export const getData = () => (dispatch) => {
    try {
        const dataResponse = await dataAPI.getData();
        dispatch(getDataAction(dataResponse));
        return Promise.resolve(dataResponse);
    } catch (error) {
        return Promise.reject(error);
    }
}

In the Component of React 在React的组件中

componentDidMount = () => {
    const {
        getData
    } = this.props;

    getData().then(function(response) {
        // I can use this response action for some UX Action.
    })
}

With using RxJS/Redux-Observable 使用RxJS / Redux-Observable

I don't know how to return promise 我不知道如何兑现承诺

In the Epic Action of React 在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
                    )
                ))
            )
        })
    );
}

In the Component of React 在React的组件中

componentDidMount = () => {
    const {
        getData
    } = this.props;

    getData().then(function(response) {
        // How to get this response result ?
    })
}

I know using Reducer is the one of way to handle, but I still want to know how to return promise. 我知道使用Reducer是处理方法之一,但我仍然想知道如何返回Promise。

Thanks guys 多谢你们

So you made a classic mistake when we are returning a promise you should not return a new Promise for the success or error but return two function: 因此,当我们返回承诺时,您犯了一个经典错误,您不应为成功或错误返回新的Promise,而应返回两个函数:

resolve -> for the sucess chaining it with then reject -> for the faileure chaining it with catch ! 解决->对于成功的链接,然后拒绝->对于失败的链接,与catch!

Hope this code will help you, tell me if you need clarification 希望这段代码对您有所帮助,告诉我是否需要澄清

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)
  }   
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM