I'm trying to understand how to resolve dependencies among stores. The problem is I have a comprehensive data tree, which need to be fetched from server with the chain of request that depends one on another.
PROBLEM: waitFor
seams not to be supposed for async requests. Suppose next event chain:
- NEED_A (look at
StoreA
) - NEED_B (look at
StoreB
) HereStoreB
doAppDispatcher.waitFor([StoreA.dispatchToken])
. But actually we want to wait forGET_A
- SOME_OTHER_ACTION (look at
StoreA
)
The third step breaks waitFor
from the second step since StoreA.dispatchToken
was called for SOME_OTHER_ACTION
.
Question: What is a true way to wait for some specific action (GET_A
)?
Let's take a look at the code (please pay attention to three PROBLEM
comments):
StoreA
var a = [];
var StoreA = assign({}, EventEmitter.prototype, {
getAProps: () => copyOfAProps(a);
asyncGetA: () => ... //Async request returns Promise
});
StoreA.dispatchToken = AppDispatcher.register((action) => {
switch(action.type) {
NEED_A:
StoreA.asyncGetA().then((data) => {
ActionCreator.getA(data); //Dispatches GET_A event
});
break;
GET_A:
a = action.data;
StoreA.emitChange();
SOME_OTHER_ACTION:
//do whatever
}
});
StoreB
var b = [];
var StoreB = assign({}, EventEmitter.prototype, {
// PROBLEM: this request depends on data fetched from StoreA.asyncGetA
asyncGetB: (A) => ...
});
StoreB.dispatchToken = AppDispatcher.register((action) => {
switch(action.type) {
//PROBLEM: NEED_B may happen before GET_A
NEED_B:
//PROBLEM: As I understand waitFor doesn't work here
AppDispatcher.waitFor([StoreA.dispatchToken]);
StoreB.asyncGetB(StoreA.getAProps()).then((data) => {
ActionCreator.getB(data);
});
GET_B:
b = action.data;
StoreB.emitChange();
}
});