ApathyBear ApathyBear - 18 days ago 10
React JSX Question

reactjs / flux: execute actions (ajax) in order

I have flux actions that are simply AJAX calls that update the store with data on success.

In my component I have a function that uses these actions:

// Insert new event
ReactActions.submitNewEvent(data)
// Insert new exceptions
ReactActions.submitNewExceptions(exception_objects)

// Merge
ReactActions.merge(data, exception_objects)


I would like to execute the first two action completely (meaning a 200 success response from the ajax method) before the third action is executed.

What is the best way to do this in a Flux-like architecture? Should I be opting for promises? Could you present an example?

Answer

Yes, promises are a good approach to solve problems like this.

Promise.all() will help you with synchronizing the last call with the previous two. Make sure that both submitNewEvent() and submitNewExceptions() return a promise that is resolved when the AJAX calls are completed:

Promise.all([
    ReactActions.submitNewEvent(data),
    ReactActions.submitNewExceptions(exception_objects)
]).then(function() {
    ReactActions.merge(data, exception_objects)
})