异步/等待来自React组件的调用操作

时间:2018-05-11 14:54:53

标签: javascript reactjs react-redux ecmascript-2017

我在反应组件中有一个调用动作lookupComplete的方法checkIfAssign,我需要等待响应并依赖此响应触发器在此方法中的另一种方法。但是接受Promise {<pending>} "result"。如何等到解决此问题?

组件:

export class Test extends Component {
  ....

  lookupComplete = (tagId = this.state.tagId) => 
    this.setState({tagId}, () => {
      let result = this.props
        .checkIfAssign(this.state.tagId, this.props.accessToken)

    result.status 
      ? this.triggerTransition(transitions.ClickCheckTag) 
      : this.triggerTransition(transitions.Test)
    })
}

export const mapDispatchToProps = dispatch => ({
  checkIfAssign: (tagId, accessToken) => 
    dispatch(TagAssignmentActions.checkTagAssignment(tagId, accessToken)),
})

行动:

export const checkTagAssignment = (tagId, token) => async dispatch => {
  dispatch({
    type: TagAssignmentActionTypes.TagAssignmentChanged,
  })

  let status, assignee, response
  try {
    response = await DeviceApi.checkTagAssignment(tagId, token)

    assignee = response.result.assignee
    status = response.result.status
  } catch (e) {
    if (e && e.status === httpStatusCode.notFound)
      status = TagStatus.NotFound
  }

  dispatch({
    type: TagAssignmentActionTypes.TagAssignmentChanged,
    status,
    assignee,
    response,
  })
  console.log(response, 'response')
  return response
}

0 个答案:

没有答案