then how is it handled through the chaining middlewares?
I think the chaining is just stopped. For example, looking at redux-thunk's code, if an action
is a function, the result of that function is returned, and next
is not called; so all the following middlewares are not processing this action
.
I think it's logical, because most of the middlewares expect action
to be object instead of function. If this function-type action is passed along, those middlewares would broke.
how can this callback or promise be later reached in the code?
I think you have to handle it right away after calling dispatch
, pretty much what you described "Just call it in chaining manner after dispatch(actionCreater)".
Like the redux-thunk
example
dispatch(makeASandwichWithSecretSauce('My partner')).then(() => {
console.log('Done!');
});
if there are more than 2 middlewares and several middlewares return
callback instead of state, are these callbacks all available to use?
I think, the answer is "no". Because the chaining is stopped. If any special action
is handled by a certain middleware, that action
cannot be passed by calling next
, otherwise the special action might break other normal middlewares.
So I guess there are several solutions:
Only use one type of special middleware, so there won't be conflicts.
If more than one special middleware, manually compose all these middlewares, make it a new middleware, then send the new one into redux
applyMiddleware
.
Use some more generic/robust middleware that could handle complex async behavior, like redux-saga
.
The idea of 2 maybe like this
const manually = store => next => action => {
if (typeof action === 'function') {
const promise = thunk(action);
const promise2 = anotherThunk(action);
// this is also tricky, because action is a function, you have to make a new object
const whatToPass = {
type: 'what is this', // depends on your need?
// any other data?
};
next(whatToPass); // chaining goes on
// maybe return this, but maybe not good,
// because every promise needs to resolve to trigger the 'then'
return Promise.all([
promise,
promise2,
]);
}
return next(action);
}