【问题标题】:Swift Promise Kit and throwsSwift Promise Kit 和 throws
【发布时间】:2016-10-20 09:06:43
【问题描述】:

所以我在我最新的 swift 应用程序中使用 PromiseKit 以及 Alamofire 来完成大部分网络代码。当我的回报不是我想要的时,我正在尝试设置我的承诺 - 这是代码的样子:

`

    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' 有什么想法吗?谢谢

【问题讨论】:

    标签: swift promisekit


    【解决方案1】:

    我认为您对 do/catch 的理解不太正确。

    Do/Catch 只是一个同步操作,因此要捕获 throw,必须在 do 块中抛出错误。在这种情况下,您在 do 块中所做的只是设置承诺。如果达到错误条件,它将在不同的上下文中异步执行 - 在您的 do catch 块之外,因此无法被捕获。

    编辑: 为了更清楚您收到错误的原因,这里是 PromiseKit 中错误的方法签名:

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

    'body' 闭包未声明为 throwing,因此您无法通过 throw 退出该上下文。要抛出,它需要像这样声明:

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

    但它不能,因为它是异步执行的。

    【讨论】:

    • 从那时起。谢谢!
    【解决方案2】:

    使用 PromiseKit 执行此操作的方式类似于:

    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) {
            //
        }
    }
    

    在上面,我假设doStuff()doOtherThing() 都是会引发错误的同步函数。因此,将它们包装在 Promise 中没有多大意义,除非您使用结果来提供异步任务,然后使用其中的结果。

    【讨论】:

      猜你喜欢
      • 2020-09-28
      • 2021-09-22
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多