处理容器组件的异步操作的最佳方法

时间:2017-01-23 15:21:14

标签: reactjs asynchronous react-native redux redux-thunk

我有两个异步操作,我必须确保它们在继续下一个代码块之前已正确执行。

代码如下所示:

createUser = () => {
    let user = this.state.user
    //create user session (this is a async action - thunk)
    //What is the correct way to wait until this method is executed?
    this.props.createSession(user)
    //if session exists means it was created
    if(this.props.session.session) {
      //What is the correct way to wait until this method is executed?
      this.props.createUser(user) //another async action
      if(this.props.userReducer.currentUser) {
        ToastAndroid.show('User registered successfully!', ToastAndroid.SHORT)
        this.props.goTo('productsContainer') //transition to the next scene
      }
    } else {
      ToastAndroid.show(this.props.session.err, ToastAndroid.SHORT)
    }
}

因为方法createSession()和createUser()是异步操作,所以我有点失去了关于如何“等待”直到第一个和第二个执行。

也许这是一个愚蠢的问题,但我是react-redux世界的新手。

1 个答案:

答案 0 :(得分:1)

鉴于行动是异步的,他们会返回承诺。所以,等待承诺:

createUser = () => {
    let user = this.state.user
    //create user session (this is a async action - thunk)
    //What is the correct way to wait until this method is executed?
    this.props.createSession(user)
        .then(() => {
            //if session exists means it was created
            if(this.props.session.session) {
              //What is the correct way to wait until this method is executed?
              this.props.createUser(user) //another async action
              if(this.props.userReducer.currentUser) {
                ToastAndroid.show('User registered successfully!', ToastAndroid.SHORT)
                this.props.goTo('productsContainer') //transition to the next scene
              }
            } else {
              ToastAndroid.show(this.props.session.err, ToastAndroid.SHORT)
            }
        })
}

等等。

如果您使用的是Babel或TypeScript,您还可以使用async / await语法:

createUser = async function() {
    let user = this.state.user
    //create user session (this is a async action - thunk)
    //What is the correct way to wait until this method is executed?
    await this.props.createSession(user)
    //if session exists means it was created
    if(this.props.session.session) {
      //What is the correct way to wait until this method is executed?
      await this.props.createUser(user) //another async action
      if(this.props.userReducer.currentUser) {
        ToastAndroid.show('User registered successfully!', ToastAndroid.SHORT)
        this.props.goTo('productsContainer') //transition to the next scene
      }
    } else {
      ToastAndroid.show(this.props.session.err, ToastAndroid.SHORT)
    }
}.bind(this)

但是,鉴于整个方法仅适用于props中传递的数据(state.user除外),这些数据似乎来自商店,因此整个方法更有意义。方法进入行动:

createUser = () => props.createSessionAndUser(this.state.user)
...
// implement entire logic in createSessionAndUser action