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



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

代码如下所示:

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 世界的新手。

鉴于操作是异步的,它们返回承诺。所以,等待承诺:

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

最新更新