If you're looking for an example of how to handle asynchronous actions in Redux, check out this link: https://github.com/gaearon/redux-thunk
The thunk middleware simplifies the process of turning async thunks into regular actions. Your "simple_action()" function needs to be a thunk, which is essentially a function that returns another function. Here's an example:
function makeASandwichWithSecretSauce(forPerson) {
return function (dispatch) {
return fetchSecretSauce().then(
sauce => dispatch(makeASandwich(forPerson, sauce)),
error => dispatch(apologize('The Sandwich Shop', forPerson, error))
);
};
}
You can then use the `dispatch` function with `makeASandwichWithSecretSauce()` like this:
store.dispatch(
makeASandwichWithSecretSauce('Me')
);
You can also chain promises by returning them from your dispatched thunks:
store.dispatch(
makeASandwichWithSecretSauce('My wife')
).then(() => {
console.log('Done!');
});
This approach allows you to create action creators that handle both synchronous and asynchronous actions smoothly.
function makeSandwichesForEverybody() {
return function (dispatch, getState) {
if (!getState().sandwiches.isShopOpen) {
return Promise.resolve();
}
dispatch(simple_action());
return dispatch(
makeASandwichWithSecretSauce('My Grandma')
).then(() =>
Promise.all([
dispatch(makeASandwichWithSecretSauce('Me')),
dispatch(makeASandwichWithSecretSauce('My wife'))
])
).then(() =>
dispatch(makeASandwichWithSecretSauce('Our kids'))
).then(() =>
dispatch(getState().myMoney > 42 ?
withdrawMoney(42) :
apologize('Me', 'The Sandwich Shop')
)
);
};
}
store.dispatch(
makeSandwichesForEverybody()
).then(() =>
console.log("Done!");
);
To manage the sequence of actions in action_creator(), it can be helpful to dispatch a simple_action before calling `action_creator()`. This ensures that the store processes the action completely before moving on to the next steps.