google/uniflow-polymer

Async action-dispatcher

eterna2 opened this issue · 6 comments

Any thoughts on making the async action dispatcher?

I am trying out uniflow for one of my projects and it is wonderful. But there is no support for async actions.

I made some changes to the dispatcher by wrapping the return of the dispatch with a Promise.resolve and chaining the them rather than iterate.

Any thoughts? If you r cool, I can make a pull request.

In case you need to launch async process in your action dispatcher, consider emitting action upon completion of async call, and have another action dispatcher handle this action.

For instance, you might have UPDATE_ITEM action calling your REST API and ITEM_UPDATED action emitted upon success (and optionally ITEM_UPDATE_FAILED on failure).

This way the code is cleaner and easier to read and write tests against. With Uniflow, we encourage you to use actions as much as possible instead of using promises or callbacks.

Thank you for ur advice. Can I further ask what would u recommend if I am waiting for multiple events to complete? (I am retrieving multiple resources)

E.g. I am using Promise.all now.

Sorry, I am still pretty new to this. I am imagining a few solutions.

  1. emit an action after each request, then the subsequent action will set a flag for the resource and check the state of all the other resources flags, and only emit a complete if everything is completed?

  2. Wrap all requests inside 1 action and use a promise.all to emit a completed action?

Sorry just one last question.

Should I keep the dispatched action (the object that is passed into the methods) immutable?

Because since each action is synchronous, if I allow the dispatched action to be mutable, I can use the action-dispatcher as middleware - modifying the data before updating the state.

Very good questions.

As to waiting for multiple events to complete, we've implemented one solution in our internal version of the library. I think it's a bit too complex and specific, so I wasn't sure about porting it to open-sourced repo. It's quite close to what you're describing in your option (1), though.

For your second question about keeping action property object immutable the answer is simple: you don't have to, and in fact you can have multiple action dispatchers acting like middleware and updating action object with new information for future actions. The order in which actions are processed is defined by the order dispatchers are declared.

Thank you very much!