2016-07-12 22 views
5

是否有可能從動作創建者返回承諾/信號,當Redux thunk成功發送某些動作時解析?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}) 
      }); 
    } 
} 

我想異步調用一些功能組件調用的doPost行動的創建者時,終極版有兩種派出POST_SUCCESS或POST_ERROR動作之後。一種解決方案是將回調傳遞給動作創建者本身,但這會使代碼變得混亂,難以掌握和維護。我也可以在while循環中輪詢Redux狀態,但這樣做效率不高。

理想情況下,解決方案將是一個承諾,當某些操作(在本例中爲POST_SUCCESS或POST_ERROR)調度時應該解決/拒絕。

handlerFunction { 
    doPost(data) 
    closeWindow() 
} 

上面的例子應該重構,所以只有在doPost()成功時才調用closeWindow()。

回答

7

當然,你可以從異步操作返回承諾:現在

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函數返回一個承諾:

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

我能保證那裏面行動的創建者之前被調用,然後裏面handlerFunction ? –

+2

是的。 'handlerFunction'內部的代碼將始終在'dispatch'代碼後被調用。 – 1ven

+0

此外,由於某些原因,示例返回當時調度的Action對象而不是響應 –