2017-11-17 1 views
0

redux thunk를 사용한 비동기 디스패치의 올바른 패턴입니까?비동기 디스패치의 올바른 패턴

//actions types 
const ADD_ARTIST = 'ADD_ARTIST' 

// action 
function AddArtist(val){ 
    return { 
    type: ADD_ARTIST, 
    payload:val 
    } 
} 


//some async events 
function async1(id){ 
    return fetch(.....) 
} 

function async2(id){ 
    return fetch(.....) 
} 

function async3(id){ 
    return fetch(.....) 
} 

function auth(id) { 
    return function (dispatch) { 
    async1(10).then((v) => dispatch(AddArtist(v))); 
    Promise.all([ 
     async2(26), 
     async3(51), 
    ]).then(
      (v) => dispatch(AddArtist(v[0] + v[1]) 
    )); 
    } 
} 


var ViewWrapper = connect(
    state => ({ 
    playlist: state.playlist, 
    artist: state.artist, 
    }), 
    dispatch => (
    { 
     dispatch, 
     auth: bindActionCreators(auth, dispatch) 
    }) 

)(View); 

버튼 :

<input type='button' onClick={() => 
this.props.dispatch(this.props.auth()) } value='dispatch mapDispatch>>>>>>>' /> 
+1

를 작성할 수 있습니다. 오류 처리가 필요합니다. –

답변

1

redux documentation에 따라, 잘 보이지만, 당신은 또한 오류 처리하는 몇 가지 코드를 적용합니다.

여기 당신은 (https://redux.js.org/docs/advanced/AsyncActions.html), 이것은 올바른 보인다 [문서]에 따라 더 좋은 방법

function auth(id) { 
    return ((dispatch) => async1(10) 
       ).then((v) => dispatch(AddArtist(v)) 
       ).then(() => 
       Promise.all([ 
        async2(26), 
        async3(51), 
       ]) 
      ).then((v) => dispatch(AddArtist(v[0] + v[1])) 
      ) 
    ) 
} 
+0

답변 해 주셔서 감사합니다. – zloctb