2016-06-18 1 views
0

그래서 Alamofire와 함께 네트워킹 코드의 대부분을 수행하는 최신의 신속한 응용 프로그램에서 PromiseKit을 사용하고 있습니다.Swift Promise Kit 및 throws

`

do{ 
     firstly({ 
      try DoStuff.doStuff() 
     }).then({ response in 
      self.array = response 
     }).error { error in 
      throw Error.GeneralError 
      print(error) 
     } 

     firstly({ 
      try DoOtherThing.otherThing() 
     }).then({ response in 
      self.stuff = response 
     }).error{ error in 
      throw TransactionError.GeneralError 
      print(error) 
     } 
    } catch { 
     let alertController = UIAlertController(title: "Network Error", message: "Network error, please try again", preferredStyle: .Alert) 
     let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in 
      // 
     } 
     alertController.addAction(OKAction) 
     self.presentViewController(alertController, animated: true) { 
      // 
     } 
    } 

`

이 코드는 도리 단지 늠름한 작동 :처럼 여기 코드가 어떻게 표시되는지를 보여줍니다 - 내 반환 내가 원하는 것을하지 않을 때 던져 설정에 내 약속을 시도하고있다 거기에 'throw'문이 없으면 오류를 인쇄하거나 거기에 경고 컨트롤러 코드를 넣으면 예상대로 작동합니다. 하지만 던지기를 추가하면 컴파일러의 붉은 깃발이 '오류'란에 표시됩니다. Cannot call value of non function type 'ErrorType' 어떤 생각을하고 있습니까? 감사합니다

답변

0

나는 do/catch의 이해가 옳지 않다고 생각합니다.

Do/Catch는 동기 작업이므로 throw를 catch하려면 do 블록에 오류가 발생해야합니다. 이 경우 do 블록 내부에서하는 모든 일은 약속을 설정하는 것입니다. 오류 조건에 도달하면 다른 상황에서 비동기 적으로 실행됩니다. do catch 블록 외부에 있으므로 catch 할 수 없습니다.

편집 :

func error(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, _ body: (ErrorType) -> Void) 

'몸'폐쇄가 너무 그러므로 당신에게 던지는으로 선언되지 않은 : 당신이 오류가 발생하는 이유를 명확하게하기 위해, 여기 PromiseKit의 오류에 대한 메소드 서명은 그 문맥을 종료하기 위해서 (때문에) 슬로우 할 수 없습니다. throw하려면 다음과 같이 선언해야합니다.

func error(policy policy: ErrorPolicy = .AllErrorsExceptCancellation, _ body: (ErrorType) throws -> Void) 

하지만 비동기 적으로 실행하므로 실행할 수 없습니다. 나는 doStuff()doOtherThing() 오류에 던져 동기식 기능이 있으리라 믿고있어, 상기에서

let stuff = firstly { 
    try DoStuff.doStuff() 
}.then { response in 
    self.array = response 
} 

let otherStuff = firstly { 
    try DoOtherThing.otherThing() 
}.then { response in 
    self.stuff = response 
} 

when(fulfilled: stuff, otherStuff).catch { _ in 
    let alertController = UIAlertController(title: "Network Error", message: "Network error, please try again", preferredStyle: .alert) 
    let OKAction = UIAlertAction(title: "OK", style: .default) { (action) in 
     // 
    } 
    alertController.addAction(OKAction) 
    self.present(alertController, animated: true) { 
     // 
    } 
} 

: 당신이 PromiseKit 함께 할 것

+0

이후로. 감사! –

0

방법은 다음과 같을 것이다. 따라서 결과를 사용하여 비동기 작업을 처리 한 다음 그 결과를 사용하지 않는 한 약속 내용을 포장하는 것은 많은 의미가 없습니다.