React,redux,redux observable:Promise解析类型

时间:2018-03-13 01:37:34

标签: reactjs typescript redux redux-observable

我正在尝试定义承诺决心的类型。 以下是代码的一部分,或者如果你想在github上查找它:https://github.com/Electra-project/Electra-Desktop/blob/master/src/app/header/epics.ts

export function getStakingInfo(action$: ActionsObservable<HeaderActions>, store: any): any {
  return action$.ofType(ActionNames.GET_STAKING_INFO)
    .map(() => store.getState().electra.electraJs) // get electraJs object from the store
    .filter((electraJs: any) => electraJs) // check if electraJs exists
    .map(async (electraJs: any) => electraJs.wallet.getStakingInfo())
    .switchMap(async (promise: Promise<WalletStakingInfo>) => new Promise((resolve) => {
      promise
        .then((data: WalletStakingInfo) => {
          resolve({
            payload: {
              ...data
            },
            type: ActionNames.GET_STAKING_INFO_SUCCESS
          })
        })
        .catch((err: any) => {
          resolve({
            type: ActionNames.GET_STAKING_INFO_FAIL
          })
        })
    }))
    .catch((err: any) =>
      Observable.of({
        type: ActionNames.GET_STAKING_INFO_FAIL
      }))
}

我收到一条错误消息,指出上面代码部分中的resolve未定义为new Promise((resolve) => {。但是我不确定这种决心​​。

任何人都可以指导我在这里应该采取什么样的决心?

1 个答案:

答案 0 :(得分:0)

您可以像这样定义自己的类型:

type Resolve = (action: { payload?: WalletStakingInfo; type: ActionNames; }) => void;

export function getStakingInfo(action$: ActionsObservable<HeaderActions>, store: any): any {
    return action$.ofType(ActionNames.GET_STAKING_INFO)
        .map(() => store.getState().electra.electraJs) // get electraJs object from the store
        .filter((electraJs: any) => electraJs) // check if electraJs exists
        .map(async (electraJs: any) => electraJs.wallet.getStakingInfo())
        .switchMap(async (promise: Promise<WalletStakingInfo>) => new Promise((resolve: Resolve) => {
            promise
                .then((data: WalletStakingInfo) => {
                    resolve({
                        payload: {
                            ...data
                        },
                        type: ActionNames.GET_STAKING_INFO_SUCCESS
                    })
                })
                .catch((err: any) => {
                    resolve({
                        type: ActionNames.GET_STAKING_INFO_FAIL
                    })
                })
        }))
        .catch((err: any) =>
            Observable.of({
                type: ActionNames.GET_STAKING_INFO_FAIL
            }))
}