javascript - Redux thunk: return promise from dispatched action -
is possible return promise/signal action creator, resolved when redux thunk has dispatched action?
consider action creator:
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}) }); } }
i want call function asynchronously in component after calling dopost action creator when redux has either dispatched post_success or post_error actions. 1 solution pass callback action creator itself, make code messy , hard grasp , maintain. poll redux state in while loop, inefficient.
ideally, solution promise, should resolve/reject when actions (in case post_success or post_error) gets dispatched.
handlerfunction { dopost(data) closewindow() }
the above example should refactored, closewindow() gets called when dopost() successful.
sure, can return promise async action:
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, able handle after dispatching async action. return response; }) .catch(errormessage => { dispatch({type: post_error, payload: errormessage}) // throwing error, able handle errors later, in component. throw new error(errormessage) }); } }
now, dispatch
function returning promise:
handlerfunction { dispatch(dopost(data)) // now, have access `response` object, returned promise in `dopost` action. .then(response => { // function called when async action succeeded. closewindow(); }) .catch(() => { // function called when async action failed. }); }
Comments
Post a Comment