0

I want to use BoltsSwift (https://github.com/BoltsFramework/Bolts-Swift).

But I am not able to handle errors correctly.

In the below sample, why the "taskHello2.continueOnSuccessWith" is running instead of "taskHello2.continueOnErrorWith" ?

Thank you

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
}

output:

=> hello1
=> error
=> Success received
Fred
  • 13
  • 1

1 Answers1

0

The function continueOnErrorWith(continuation:) only runs when there is an error—the task is faulted.

In your testTask() function, taskHello1 is executed—or succeeded—and hence 'hello1' is printed to console.

In code:

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

since taskHello1 had already met success, the code inside the closure is executed and 'error' is printed.

Inside code:

_ = taskHello2.continueOnErrorWith(continuation: { (task) -> Task<String> in
    let taskResult = self.echo("Error received")
    return taskResult
})

since taskHello2 had not met error, the code inside the closure is not executed and 'Error received' is not printed to console.

Similarly in code:

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

since taskHello2 had met success, the code inside the closure is executed and 'Success received' is printed.

naeemjawaid
  • 504
  • 3
  • 10
  • thank naeemjawaid for your answer. It is exactly what I don't understand: Since taskHello2 is the result of taskHello1.continueOnSuccessWith which return the result of self.echo("error") which return a faulted task, taskHello2 should be a faulted task, not? If not, what have I to do to have taskHello2 as a faulted task ? – Fred Aug 28 '18 at 03:38
  • I up my question. @naeemjawaid ? – Fred Aug 29 '18 at 17:07