2016-07-12 4 views
5

Redux Thunk가 특정 작업을 성공적으로 발송할 때 해결되는 약속 작성자로부터 신호를 반환 할 수 있습니까? 내가 돌아 오는이 하나가 POST_SUCCESS 또는 POST_ERROR 작업을 파견가있는 경우 의 doPost 행동 작성자를 호출 한 후 비동기 구성 요소에 을 어떤 함수를 호출 할Redux thunk : 파견 된 조치로 약속을 반환하십시오.

function doPost(data) { 
    return (dispatch) => { 
     dispatch({type: POST_LOADING}); 
     Source.doPost() // async http operation 
      .then(response => { 
       dispatch({type: POST_SUCCESS, payload: response}) 
      }) 
      .catch(errorMessage => { 
       dispatch({type: POST_ERROR, payload: errorMessage}) 
      }); 
    } 
} 

:

이 작업 창조자를 생각해 보자. 한 가지 해결책은 콜백을 액션 생성자 자체에 전달하는 것이지만, 코드를 지저분하게 만들고 파악하고 유지하기 어렵게 만듭니다. while 루프에서도 Redux 상태를 폴링 할 수는 있지만 비효율적입니다.

솔루션은 특정 작업 (이 경우 POST_SUCCESS 또는 POST_ERROR)이 발송 될 때 해결/거부해야하는 것이 가장 이상적입니다.

handlerFunction { 
    doPost(data) 
    closeWindow() 
} 

위의 예제는 리팩토링되어야하므로 doPost()가 성공적 일 때만 closeWindow()가 호출됩니다.

답변

7

물론, 당신은 비동기 작업에서 약속을 반환 할 수 있습니다 handlerFunction 안에 그 전에 호출되는

handlerFunction { 
    dispatch(doPost(data)) 
     // Now, we have access to `response` object, which we returned from promise in `doPost` action. 
     .then(response => { 
      // This function will be called when async action was succeeded. 
      closeWindow(); 
     }) 
     .catch(() => { 
      // This function will be called when async action was failed. 
     }); 
} 
+0

내가 그 다음 내 행동 작성자을 보장 할 수 있습니다 :

function doPost(data) { return (dispatch) => { dispatch({type: POST_LOADING}); // Returning promise. return Source.doPost() // async http operation .then(response => { dispatch({type: POST_SUCCESS, payload: response}) // Returning response, to be able to handle it after dispatching async action. return response; }) .catch(errorMessage => { dispatch({type: POST_ERROR, payload: errorMessage}) // Throwing an error, to be able handle errors later, in component. throw new Error(errorMessage) }); } } 

이제 dispatch 함수는 약속을 반환 ? –

+2

예. 'handlerFunction' 내부의 코드는'dispatch' 코드 이후에 항상 호출됩니다. – 1ven

+0

또한 어떤 이유로 든 응답이 아닌 내부에 전달 된 Action 객체를 반환합니다. –