2017-01-23 6 views
0

두 블록의 비동기 작업을 수행하여 다음 코드 블록을 사용하기 전에 제대로 실행되었는지 확인해야합니다. 메소드 createSession()과는 createUser()는 첫 번째와 두 번째까지 내가 조금 "대기"하는 방법에 대해 잃었어요 비동기 작업이컨테이너 구성 요소에서 비동기 작업을 처리하는 가장 좋은 방법

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

때문에 :

코드는 다음과 같습니다 하나가 실행됩니다.

어쩌면 그것은 바보 같은 질문이지만 나는 반응을 줄이는 세계에서 초보자입니다.

답변

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) 

을 감안할 때, 그러나 전체 방법은 state.user을 제외하고 (props에 전달되는 데이터를 통해서만 작동), 어쨌든 상점에서 오는 것처럼 보이면 전체 메소드를 액션으로 전환하는 것이 더 적합합니다.

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