Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@christianchown
Last active December 5, 2019 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save christianchown/73a5ebc914e5303e0a00833c82cd3109 to your computer and use it in GitHub Desktop.
Save christianchown/73a5ebc914e5303e0a00833c82cd3109 to your computer and use it in GitHub Desktop.
Custom async Redux middleware
const userMiddleware = ({ getState, dispatch }) => next => async action => {
const result = next(action);
switch (action.type) {
case SOME_ACTION:
const asyncResult = await somethingAsync();
dispatch(anotherAction(asyncResult));
break;
case SOME_OTHER_ACTION:
const { slice: { stateVariable } } = getState();
await someProcess(stateVariable);
break;
}
return result;
}
@Constantiner
Copy link

Sorry for the stupid question, but why you need this:

return Promise.resolve(result);

from async function considering async functions always return Promise and it will be the same as just:

return result;

?

@plandem
Copy link

plandem commented Nov 29, 2019

@Constantiner it's really funny to meet you here as the only commentator! :) RIA times ;)

@Constantiner
Copy link

@christianchown
Copy link
Author

@Constantiner good spot! I originally didn't have the method flagged as async, and had that to return a Promise... will change, thanks!

@markerikson
Copy link

markerikson commented Dec 5, 2019

Hmm. One thing to note: by marking it as async action =>, you are now causing it to always return a promise, which also wraps everything returned by the middleware pipeline after this in a promise as well.

This may not be an issue depending on your setup, but FYI.

@plandem
Copy link

plandem commented Dec 5, 2019

omg, that gist is like meeting of old friends now. Before it was @Constantiner and now @markerikson (hello, redux-orm) :)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment