我想使用 BoltsSwift ( https://github.com/BoltsFramework/Bolts-Swift )。
但我无法正确处理错误。
在下面的示例中,为什么运行的是“taskHello2.continueOnSuccessWith”而不是“taskHello2.continueOnErrorWith”?
谢谢
func testTask() {
let taskHello1 = echo("hello1")
let taskHello2 = taskHello1.continueOnSuccessWith(continuation: { (task) -> Task<String> in
let taskResult = self.echo("error")
return taskResult
})
_ = taskHello2.continueOnErrorWith(continuation: { (task) -> Task<String> in
let taskResult = self.echo("Error received")
return taskResult
})
_ = taskHello2.continueOnSuccessWith(continuation: { (task) -> Task<String> in
let taskResult = self.echo("Success received")
return taskResult
})
}
func echo(_ text: String) -> Task<String> {
let taskCompletionSource = TaskCompletionSource<String>()
print("=> \(text)")
switch (text) {
case "error":
let error = NSError(domain: "domain", code: -1, userInfo: ["userInfo": "userInfo"])
taskCompletionSource.set(error: error)
case "cancel":
taskCompletionSource.cancel()
default:
taskCompletionSource.set(result: text)
}
return taskCompletionSource.task
}
输出:
=> hello1
=> error
=> Success received
最佳答案
函数continueOnErrorWith(continuation:)
仅在出现错误时运行——任务发生故障。
在您的 testTask()
函数中,taskHello1
被执行(或成功),因此 'hello1' 被打印到控制台。
在代码中:
let taskHello2 = taskHello1.continueOnSuccessWith(continuation: { (task) -> Task<String> in
let taskResult = self.echo("error")
return taskResult
})
由于 taskHello1
已经成功,因此闭包内的代码被执行并且'错误'打印。
内部代码:
_ = taskHello2.continueOnErrorWith(continuation: { (task) -> Task<String> in
let taskResult = self.echo("Error received")
return taskResult
})
由于taskHello2
有未遇到错误,闭包内的代码未执行并且“收到错误” 未打印到控制台。
代码中类似:
_ = taskHello2.continueOnSuccessWith(continuation: { (task) -> Task<String> in
let taskResult = self.echo("Success received")
return taskResult
})
由于taskHello2
成功,闭包内的代码被执行并且'成功收到'打印。
关于ios - Bolt-Swift : error handling,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52046135/