我想使用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
没有遇到错误,所以闭包内的代码没有执行,并且'Error received'没有打印到控制台。
同样在代码中:
_ = taskHello2.continueOnSuccessWith(continuation: { (task) -> Task<String> in
let taskResult = self.echo("Success received")
return taskResult
})
因为taskHello2
已经成功,所以关闭内部的代码被执行并且打印出“收到成功”。