Skip to content

Instantly share code, notes, and snippets.

@leafmind
Created August 29, 2015 19:57
Show Gist options
  • Save leafmind/499575ed5f874887a8bd to your computer and use it in GitHub Desktop.
Save leafmind/499575ed5f874887a8bd to your computer and use it in GitHub Desktop.
export function promiseMiddleware() {
function isPromise(value) {
return value && typeof value.then === 'function';
}
return next => action => {
if (!isPromise(action.promise)) {
return next(action);
}
const { types } = action;
const promise = action.promise;
const [ PENDING, FULFILLED, REJECTED ] = types;
/**
* Dispatch the first async handler. This tells the
* reducer that an async action has been dispatched.
*/
next({
type: PENDING
});
/**
* Return either the fulfilled action object or the rejected
* action object.
*/
return promise.then(
response => next({
response: JSON.parse(response.text).data || JSON.parse(response.text),
type: FULFILLED
}),
error => next({
error: JSON.parse(error.response.text).error,
type: REJECTED
})
);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment