我正在尝试使用闭包概念来获取回调函数中的附加参数。出于某种原因,它无法正常工作。以下是供参考的代码。
export function loadConfigData(session) {
return function(dispatch) {
// API URL to get the config details
const url = session.apiHost + '/config';
const headers = {'Accept': 'application/json','Content-Type': 'application/json',key: session.key};
// Make fetch API call to get the config data with same-origin to enable fetch to send the cookie with API call.
return fetch(url,{credentials: 'same-origin',headers,method: 'GET'})
.then(processAPIResponse)
.then(loadConfigDataSuccessHandler)
.catch(loadConfigDataErrorHandler);
}
}
export const processAPIResponse = (response)=> {
if ( !response.ok ) {
return Promise.reject(response);
}
return Promise.resolve(response.json());
};
export const loadConfigDataErrorHandler = (response)=> {
return function(dispatch) {
dispatch(receiveConfigError(new Error("Bad response from server")));
return Promise.reject(response);
};
};
export const loadConfigDataSuccessHandler = (configObj)=> {
// Following function is not getting execute.
return function(dispatch) {
// In case of success, start action to update the data
dispatch(receiveConfigData(configObj));
// Resolve promise
return Promise.resolve(configObj);
};
};
问题:由于某种原因,“loadConfigDataSuccessHandler”返回的函数没有得到执行,因此我的成功处理程序上的业务逻辑没有执行。
注意:此代码段来自redux-action,因此请忽略使用“dispatch”
使用回调更新的工作代码:
要添加更多细节,如果不使用闭包和回调那么它可以工作,但是,我认为这不是一个干净的方法。以下是有效的回调方法。
export const loadConfigDataSuccessHandler = (configObj,dispatch)=> {
// In case of success, start action to update the data
dispatch(receiveConfigData(configObj));
return configObj;
};
export const loadConfigDataErrorHandler = (response,dispatch)=> {
dispatch(receiveConfigError(new Error("Bad response from server")));
return response;
};
export function loadConfigData(session) {
return function(dispatch) {
// Request to load the user data, set loading flag is true to show loading screen
dispatch(requestConfigData());
// API URL to get the user details
const url = session.apiHost + API_CONTEXT_PATH + '/config';
const headers = getHTTPHeader(session.blueboxpublic,session.blueboxvalues);
// Make fetch API call to get the user data with same-origin to enable fetch to send the cookie with API call.
return fetch(url,{credentials: 'same-origin',headers,method: 'GET'})
.then(processAPIResponse)
.then((configObj)=>loadConfigDataSuccessHandler(configObj,dispatch))
.catch((configObj)=>loadConfigDataErrorHandler(configObj,dispatch))
.catch(handleAPISystemDown)
.catch(loadConfigDataErrorHandler);
}
}