我正在尝试设置redux,react-redux和redux-thunk。一般认为进展顺利,但我对将多个异步行为链接在一起时应该如何看待有疑问。
具体来说,我有一个场景,可以通过另一个可以调用它们的动作单独或间接调用这些动作。我的问题是,如果我想成为惯用语,应该如何撰写selectItem
?
action.js
export function fetchByContext(contextId) {
return dispatch => {
_fetchByContext(messages => {
dispatch({ type: RECEIVE_MESSAGES, ... });
});
};
};
export function subscribeByContext(contextId) {
return dispatch => {
_subscribeByContext(messages => {
dispatch({ type: RECEIVE_MESSAGES, ... });
});
};
};
export function selectItem(contextId) {
return dispatch => {
subscribeByContext(contextId)(dispatch);
fetchByContext(contextId)(dispatch);
};
};
答案 0 :(得分:0)
我认为关键是(ref):
内部函数的任何返回值都将作为dispatch本身的返回值
如果fetchByContext()
,subscribeByContext()
的内部函数返回一个承诺,则这些函数可以串联链接或从selectItem()
并行运行。假设_fetchByContext()
和_subscribeByContext()
都没有返回承诺,未经测试的实现将是:
export function fetchByContext(contextId) {
return dispatch => {
return new Promise((resolve, reject) => {
_fetchByContext(messages => {
dispatch({ type: RECEIVE_MESSAGES, ... });
resolve(messages);
});
});
};
};
export function subscribeByContext(contextId) {
return dispatch => {
return new Promise((resolve, reject) => {
_subscribeByContext(messages => {
dispatch({ type: RECEIVE_MESSAGES, ... });
resolve(messages);
});
});
};
};
export function selectItem(contextId) {
return dispatch => {
// CALL IN SERIES
return dispatch(subscribeByContext(contextId))
.then(() => dispatch(fetchByContext(contextId)));
// CALL IN PARALLEL (alternative to the code above; this is probably not what you want - just keeping for reference)
return Promise.all(
dispatch(subscribeByContext(contextId)),
dispatch(fetchByContext(contextId))
);
};
}
请再次注意上面的代码是未经测试的,只是希望能给出一般解决方案的想法。