Skip to content

Add separate project for async-thunk implementation #19

@ttamminen

Description

@ttamminen

@aikoven provided a solution for redux-thunk integration and I think this should be a separate package with the util + documentation. I use redux-thunk, so I can contribute to the usage documentation.

I have modified it slightly for readability and added TError generic.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions