所以下面是一个可运行的脚本,它演示了我正在尝试(并且失败)描述的问题。它还包括一个潜在的解决方案(使用中间件包装器)。很想知道是否有更优雅的解决方案......
var { createStore, applyMiddleware } = require( "redux" );
var dispatchResult;
// create the results object to be passed along the middleware chain, collecting
// results as it goes
const genesis = _store => next => action => {
next( action );
return {};
};
const wrapper = ( key, mware ) => store => next => action => {
// extract the results object by storing the result of next(action)
// when it is called within the middleware
var extractedResult;
function modifiedNext( action ) {
extractedResult = next( action );
return extractedResult;
}
// get the result of this middleware and append it to the results object
// then pass on said results object...
var newResult = mware( store )( modifiedNext )( action );
extractedResult[ key ] = newResult;
return extractedResult;
};
// create standard logging middleware
const logger = store => next => action => {
let result = next( action );
console.log( `value is: ${ store.getState() }.`);
return result;
};
// create middleware that returns a number
const gimme = val => _store => next => action => {
next( action );
return val;
};
// create our super simple counter incrementer reduer
function reducer( state = 0, action ) {
if( action.type === "INC" )
return state + 1;
return state;
}
// first lets try running this without the wrapper:
dispatchResult = createStore( reducer, applyMiddleware(
gimme( 4 ),
logger,
gimme( 5 )
) ).dispatch( { type : "INC" } );
// will return only 4 (the result of the outermost middleware)
// we have lost the 5 from the gimme(5) middleware
console.log( dispatchResult );
// now we include the middleware wrapper and genesis middleware
dispatchResult = createStore( reducer, applyMiddleware(
wrapper( "g4", gimme( 4 ) ),
logger,
wrapper( "g5", gimme( 5 ) ),
genesis
) ).dispatch( { type : "INC" } );
// we will now return { g4 : 4, g5 : 5 }
// we have preserved the results of both middlewares
console.log( dispatchResult );