2017-03-17 5 views
1

다음 서비스가 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)); 
    }); 
} 

그래서 나는 getAllPropertiesByAppId를 호출하고 모든 것이 괜찮 때 조치를 ShoppingCartPropertiesLoaded 및 ShoppingCartPropertiesDone 파견 initProperties 액션 창조자를 호출 할 때.

내가 저장하기 위해 연결 간단한 구성 요소를 가지고 렌더링 방법은

export default class TotalPriceList extends React.Component<ITotalPriceListProps, void> { 

public render(): JSX.Element { 

    throw 'SomeError'; 
} 
} 

처리되지 않은 예외가 가져 오기의 catch 문에 끝을 실행하는 경우 구성 요소 오류가 발생합니다.

약속을 종료하는 방법과 같은 것을 놓쳤는가? 가져 오기의 catch 문에서 콜백 예외를 피하기 위해 약속 이외의 함수/콜백을 호출하는 방법이 빠졌습니까? 당신이 약속 체인 내부 예외를 캐치하지 않으려면 당신의 도움을 주셔서 대단히

덕분에

답변

2

getAllPropertiesByAppId 함수의 매개 변수로서 성공 및 오류 콜백이 있습니다.

그리고 실제 문제입니다. 은 항상 비동기 함수에서 약속을 반환해야합니다. 콜백 매개 변수 사용을 중단하십시오!

코드는 부수적으로 처리되지 않은 거부로 문제를 해결할 수

/** 
* Get all properties 
*/ 
public getAllPropertiesByAppId(appliactionId: string): Promise<IPropertyItem[]> { 
    //set up createRequestStr and requestInit 
    return fetch(createRequestStr, requestInit) 
// ^^^^^^ 
    .then<IPropertyItem[]>((response: Response) => { 
     if (response.status===401) { 
      throw new UnAuthorizedException(); 
     } 
     return response.json<IPropertyItem[]>(); 
    }); 
} 

이 읽어야합니다. 사슬을 끝내지 않고 약속을 되풀이함으로써, 평소대로 호출자에게 오류 처리 책임을 위임합니다. 또한 호출자는 약속 콜백에서 수행하는 작업에 대해 묵시적으로 책임이 있습니다. 약속 반환 메서드와 전혀 관련이 없습니다.

그러므로 당신은 내가 찾던 정확히입니다

service.getAllPropertiesByAppId(appId).then((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)); 
}).catch((reason: any) => { 
    // error handling for a failed dispatch 
}); 
+0

완벽한을 사용하십시오! 감사 Bergi! –

0

, 당신은 단지 마지막에 .catch 호출을 제거해야합니다.

그러나이 오류는 try {} catch (error) {} 블록을 사용하여 catch 할 수 없습니다. 대신, 최상위 레벨에서 unhandledRejection을 받게 될 지점까지 버블 링됩니다.

올바르게 이해했다면 콜백 (success)을 getAllPropertiesByAppId으로 전달하면 콜백을 호출하는 약속이 반환됩니다. 기본적으로 fetch(…).then(success)입니다. 따라서 여러분이 경험하는 것은 약속에 포함 된 함수 내에서 예외의 정의 된 행위에 완전히 해당됩니다.

연속 전달 스타일 (콜백)과 약속을 혼합하는 대신 약속을 항상 사용하도록 전환 할 수 있습니다. 파견 구성 요소 내부 예외를 던지는

는 (의사 코드-JS에, 죄송 화면 반전되지 않음) 같은

뭔가

class Service { 
    getAllPropertiesByAppId (appId) { 
    return fetch(createRequestStr, requestInit) 
      .then(response => response.json()); 
    } 
}; 

// … 

service.getAllPropertiesByAppId(…) 
.then(dispatchAllTheThings) 
.catch(error => { console.log(…); dispatch(…) }) 

다음 dispatchAllTheThings에 대한 호출 후 약속 체인의 .catch 내부에 잡힐 것 .