You should consider using async/await pattern which handles that scenario well. Your code would then look like this:
const sendData = async message => {
const messageId = await sendDataApi(message)
const details = await getDetails(messageId)
return details
}
However, if you are not able to use newest language features you may use Promise
s. Keep in mind that the code will be more prone to callback-hell and that they might also need polyfilling.
The same code with promises would look like this:
const sendData = message => {
sendDataApi(message)
.then(messageId => getDetails(messageId))
}
This code is a mere example of the issues with Promises because it can be reduced just to sendDataApi(message).then(getDetails)
. Problems arise when there are complex conditional logic, error handling, more tasks, and parameter passing.
React handles asynchrony very poorly so do the Redux. You need to use redux-thunk, redux-saga or another middleware. With that, you will be able to dispatch another action from the action creator (continuation
, trunk
, saga
- you name it). It can become tedious, require much boilerplate, and be very difficult to debug. You may consider leaving Redux synchronous state management and consider other solutions (RxJS maybe?) for those kinds of problems.
Please see an example of using Promises to chain two asynchronous calls using React's default setState
(see console output).
With redux-thunk the implementation might look like this (other actions not show, no error handling etc.):
...
const sendData = message => {
return dispatch => {
return sendDataApi(message).then(
messageId => dispatch(getDetails(messageId)),
);
};
}