AllenYuan

http - middleware

Apr 23rd, 2020
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const promiseMiddleware = store => next => action => {
  2.   // if the action's payload is a promise, trigger this middleware
  3.   if (isPromise(action.payload)) {
  4.     // let promise succeed/fail
  5.     action.payload.then(
  6.       // if it succeeds, mutate payload into the promised data and
  7.       // dispatch action to store
  8.       res => {
  9.         action.payload = res;
  10.         store.dispatch(action);
  11.       },
  12.       // failure => set an error flag on action and mutate payload into
  13.       // the error message. dispatch action to store
  14.       error => {
  15.         action.error = true;
  16.         action.paylaod = error.response.body;
  17.         store.dispatch(action);
  18.       }
  19.     );
  20.  
  21.     return;
  22.   }
  23.  
  24.   // if the action payload is not a promise, send the action over to the next middleware
  25.   // or dispatch it to the store if this is the last middleware in the chain
  26.   next(action);
  27. }
  28.  
  29. function isPromise(v) {
  30.   return v && typeof v.then === 'function';
  31. }
  32.  
  33. export {
  34.   promiseMiddleware
  35. };
Advertisement
Add Comment
Please, Sign In to add comment