1

所以我在我最新的 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) {
            //
        }
    }

`

如果我在那里没有“抛出”语句,那么这段代码就可以正常工作——如果我只是打印错误,或者把我的警报控制器代码放在那里,就可以按预期工作。但是当我添加抛出时,我在“错误”行上得到一个编译器红旗,上面写着有Cannot call value of non function type 'ErrorType'什么想法吗?谢谢

4

2 回答 2

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 中没有多大意义,除非您使用结果来提供异步任务,然后使用该结果。

于 2017-05-13T01:18:39.990 回答
1

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

Do/Catch 只是一个同步操作,因此要捕获 throw,必须在 do 块中抛出错误。在这种情况下,你在 do 块中所做的就是设置 Promise。如果达到错误条件,它将在不同的上下文中异步执行 - 在您的 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)

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

于 2016-06-18T19:28:18.570 回答