Skip to content

Instantly share code, notes, and snippets.

@ttamminen
Last active July 19, 2019 06:34
Show Gist options
  • Save ttamminen/fa3a4030efbb85701d9fe58a039fe19d to your computer and use it in GitHub Desktop.
Save ttamminen/fa3a4030efbb85701d9fe58a039fe19d to your computer and use it in GitHub Desktop.
Helper function that adds action dispatching to promise
import { AsyncActionCreators } from 'typescript-fsa'
// https://github.com/aikoven/typescript-fsa/issues/5#issuecomment-255347353
function wrapAsyncWorker<TParameters, TSuccess, TError>(
asyncAction: AsyncActionCreators<TParameters, TSuccess, TError>,
worker: (params: TParameters) => Promise<TSuccess>,
) {
return function wrappedWorker(dispatch, params: TParameters): Promise<TSuccess> {
dispatch(asyncAction.started(params));
return worker(params).then(result => {
dispatch(asyncAction.done({ params, result }));
return result;
}, (error: TError) => {
dispatch(asyncAction.failed({ params, error }));
throw error;
});
}
}
export default wrapAsyncWorker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment