FuturaAsync

Build Status Platforms codebeat badge codecov Swift Package Manager compatible SwiftVersion Contact

Futura 工具项目的一部分。

为 iOS、macOS 和 Linux 提供 Promise 实现。

通过 Swift Package Manager 使用

.package(url: "https://github.com/kaqu/FuturaAsync.git", from: "0.9.0"),

用法示例

let promise = Promise<Int>()
let future = promise.future
future
    .thenSuccess {
        print("Success: \($0)")
    }
    .thenFailure {
        print("Error: \($0)")
    }
    .mapValue {
        return String($0)
    }
    .thenSuccess {
        print("Success(mapped): \($0)")
    }
    .thenFailure {
        print("Error(mapped): \($0)")
    }
    .recoverable { err in
        if (err as? String) == "recoverable" {
            return "Recovery!"
        } else {
            throw err
        }
    }
    .thenSuccess {
        print("Success(mapped, recoverable): \($0)")
    }
    .thenFailure {
        print("Error(mapped, recoverable): \($0)")
    }
    .map {
        switch $0 {
        case let .value(val):
            return val
        case .error:
            return "Errors sometimes happen"
        }
    }
    .then { (val: String) in
        print("Always success(mapped, recoverable, map to Future form FailableFuture): \(val)")
    }

调用

promise.fulfill(with: 9)

打印

Success: 9
Success(mapped): 9
Success(mapped, recoverable): 9
Always success(mapped, recoverable, map to Future form FailableFuture): 9

调用

promise.break() // cancel

打印

Error: cancelled
Error(mapped): cancelled
Error(mapped, recoverable): cancelled
Always success(mapped, recoverable, map to Future form FailableFuture): Errors sometimes happen

调用

promise.break(with: "recoverable" as Error)

打印

Error: recoverable
Error(mapped): recoverable
Success(mapped, recoverable): Recovery!
Always success(mapped, recoverable, map to Future form FailableFuture): Recovery!