stackjlei stackjlei - 1 year ago 151
React JSX Question

How does react redux promise middleware send the resulting action to the dispatch?

I'm trying to learn about middleware for promises through the react redux docs but don't understand the

part below:

const vanillaPromise = store => next => action => {
if (typeof action.then !== 'function') {
return next(action)

return Promise.resolve(action).then(store.dispatch)

How does the
know what to dispatch? The action wasn't passed in as an argument like

return Promise.resolve(action).then(function (action) {store.dispatch(action})

so I don't understand how dispatch receives the action.

Answer Source

I hope I can help with this explanation.

lets look at what you are familiar with:

return Promise.resolve(action)
    .then(function (action) { store.dispatch(action)} )

You see this part:

function (action) { store.dispatch(action)} 

That is just a function waiting to be passed the "action" property.

Now, when we look at what you are having issues wrapping your brain around is this:

return Promise.resolve(action)
  .then(store.dispatch) // <--- this part

the "dispatch" is just a function, and it is expecting, in this case, an argument. Most likely, an object - like so:

store.dispatch({ type: 'MY_ACTION_TYPE' })}

now, you "could" wrap it in a closure, like so, and it will look familiar:

.then( (action) => {

but, do we really need to "wrap" it in an anonymous function? Not really, so we just can put: store.dispatch, and it is function "waiting" to be passed the argument from the return of the promise. think of it like this:

 var MultiplyByTwo = (x) => x * 2

// see here, this function is gonna be called with the resolution with the 5

when we examine the function "MultipleByTwo" -- it has that familiar signature you know about: (x) => x * 2

If we just remove the function name, its the same thing:

Promise.resolve(5).then((x) => x * 2)

I hope that was helpful and I hope I actually answered your question. If not, let me know.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download