我在TypeScript中有從後端獲取數據的服務。正確的承諾處理成功和錯誤回調
作爲函數getAllPropertiesByAppId的參數,我有一個成功和錯誤回調。
export class PropertyService implements IPropertyService {
/**
* Get all properties
*/
public getAllPropertiesByAppId(appliactionId: string, success: (properties: Array<IPropertyItem>) => void, error: (error: any) => void): void {
//set up createRequestStr and requestInit
fetch(createRequestStr, requestInit)
.then<IPropertyItem[]>((response: Response) => {
if (response.status===401) {
throw new UnAuthorizedException();
}
return response.json<IPropertyItem[]>();
})
.then((response: IPropertyItem[]) => {
success(response);
})
.catch((reason: any) => {
//error handling
}
});
}
然後我在我的行動的創建者使用這項服務:
initProperties: (appId: string): ActionCreator => (dispatch: Redux.Dispatch, getState:() => IApplicationState) => {
"use strict";
console.log("ShoppingCart initProperties - Request all Property");
var service: IPropertyService = kernel.get<IPropertyService>("IPropertyService");
service.getAllPropertiesByAppId(appId, (properties: Array<IPropertyItem>): void => {
dispatch(new ShoppingCartPropertiesLoaded(appId, properties));
dispatch(new ShoppingCartPropertiesDone(appId, System.Init.Done));
}, (error: any): void => {
console.log("ShoppingCart initProperties - error:" + error);
dispatch(new ShoppingCartPropertiesDone(appId, System.Init.Error));
});
}
所以,當我打電話initProperties行動的創建者調用getAllPropertiesByAppId,當一切都很好,我會派遣行動ShoppingCartPropertiesLoaded和ShoppingCartPropertiesDone。
我有連接到存儲簡單的組件,並在Render方法執行
export default class TotalPriceList extends React.Component<ITotalPriceListProps, void> {
public render(): JSX.Element {
throw 'SomeError';
}
}
未處理的異常在獲取的catch語句結束了該組件將拋出錯誤。
我是否錯過了如何正確退出諾言或甚至更好地如何從語句和退出諾言中調用函數/回調,以避免catch語句中的回調異常?
非常感謝您的幫助
完美,這正是我一直在尋找!謝謝Bergi! –