我有以下的中間件,我用它來打電話類似的異步調用:Promise.catch在終極版中間件被調用的無關減速
import { callApi } from '../utils/Api';
import generateUUID from '../utils/UUID';
import { assign } from 'lodash';
export const CALL_API = Symbol('Call API');
export default store => next => action => {
const callAsync = action[CALL_API];
if(typeof callAsync === 'undefined') {
return next(action);
}
const { endpoint, types, data, authentication, method, authenticated } = callAsync;
if (!types.REQUEST || !types.SUCCESS || !types.FAILURE) {
throw new Error('types must be an object with REQUEST, SUCCESS and FAILURE');
}
function actionWith(data) {
const finalAction = assign({}, action, data);
delete finalAction[CALL_API];
return finalAction;
}
next(actionWith({ type: types.REQUEST }));
return callApi(endpoint, method, data, authenticated).then(response => {
return next(actionWith({
type: types.SUCCESS,
payload: {
response
}
}))
}).catch(error => {
return next(actionWith({
type: types.FAILURE,
error: true,
payload: {
error: error,
id: generateUUID()
}
}))
});
};
我然後在組件的componentWillMount
做以下電話:
componentWillMount() {
this.props.fetchResults();
this.props.fetchTeams();
}
fetchTeams
例如將派遣一個由中間件處理的動作,看起來像這樣:
export function fetchTeams() {
return (dispatch, getState) => {
return dispatch({
type: 'CALL_API',
[CALL_API]: {
types: TEAMS,
endpoint: '/admin/teams',
method: 'GET',
authenticated: true
}
});
};
}
調度這兩個成功操作並從還原器返回新狀態。這兩個減速看起來相同,下面是Teams
減速機:
export const initialState = Map({
isFetching: false,
teams: List()
});
export default createReducer(initialState, {
[ActionTypes.TEAMS.REQUEST]: (state, action) => {
return state.merge({isFetching: true});
},
[ActionTypes.TEAMS.SUCCESS]: (state, action) => {
return state.merge({
isFetching: false,
teams: action.payload.response
});
},
[ActionTypes.TEAMS.FAILURE]: (state, action) => {
return state.merge({isFetching: false});
}
});
組件然後將呈現調度另一個動作的另一個組件:
render() {
<div>
<Autocomplete items={teams}/>
</div>
}
自動完成,然後分派在其componentWillMount
一個動作:
class Autocomplete extends Component{
componentWillMount() {
this.props.dispatch(actions.init({ props: this.exportProps() }));
}
在SUCCESS減速器調用後調用的自動完成縮減器中發生錯誤從父組件的componentWillUpdate
但由於某種原因,從第一代碼片段中間件的catch處理原來的電話和fetchResults
被調用:
return callApi(endpoint, method, data, authenticated).then(response => {
return next(actionWith({
type: types.SUCCESS,
payload: {
response
}
}))
}).catch(error => {
return next(actionWith({
type: types.FAILURE,
error: true,
payload: {
error: error,
id: generateUUID()
}
}))
});
};
我不明白爲什麼catch處理程序被調用爲我原以爲這個承諾已經解決了。
你確實是對的。在下一個勾號上分配操作時,我會得到正確的堆棧跟蹤。 我認爲循環有一些它正在使用的排隊。我將深入研究這一點。感謝您的幫助。 – dagda1