2017-01-23 52 views
0

我有兩個異步操作,我必須確保在執行下一代碼塊之前它們已被正確執行。從容器組件處理異步操作的最佳方法

的代碼看起來是這樣的:

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()是異步的行動,我有點失去了關於如何「等待」,直到第一個和第二一個被執行。

也許這是一個愚蠢的問題,但我是在反應redux世界的新手。

回答

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

依此類推。

如果您使用巴貝爾或打字稿,您還可以使用異步/ 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