0

我想使用 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
4

1 回答 1

0

该函数continueOnErrorWith(continuation:)仅在出现错误时运行——任务出现故障。

在您的testTask()函数中,taskHello1执行或成功,因此将“hello1”打印到控制台。

在代码中:

let taskHello2 = taskHello1.continueOnSuccessWith(continuation: { (task) -> Task<String> in
        let taskResult = self.echo("error")
        return taskResult
    })

由于taskHello1已经遇到了 success ,因此执行闭包内的代码并打印“错误” 。

内部代码:

_ = 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遇到了 success ,因此执行闭包内的代码并打印“收到成功” 。

于 2018-08-27T21:36:46.980 回答