Skip to content

Instantly share code, notes, and snippets.

@brianneisler
Created March 2, 2018 06:02
Show Gist options
  • Save brianneisler/0e59d3d72621dbab35c987c23c25f74e to your computer and use it in GitHub Desktop.
Save brianneisler/0e59d3d72621dbab35c987c23c25f74e to your computer and use it in GitHub Desktop.
Promise Middleware
import isPromise from 'is-promise';
const defaultTypes = ['PENDING', 'FULFILLED', 'REJECTED'];
export default function promiseMiddleware() {
return ({dispatch, getState}) => {
return next => action => {
if (typeof action === 'function') {
return action(dispatch, getState);
}
if (!isPromise(action.payload)) {
return next(action);
}
const { type, payload, ...rest } = action;
const [ PENDING, FULFILLED, REJECTED ] = defaultTypes;
/**
* Dispatch the first async handler. This tells the
* reducer that an async action has been dispatched.
*/
next({
type: `${type}_${PENDING}`
});
return payload.then(
(resolved) => next({type: `${type}_${FULFILLED}`, payload: resolved, ...rest}),
(error) => next({type: `${type}_${REJECTED}`, payload: error, ...rest})
);
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment