Files
swift-nio/Sources/NIOCore/DispatchQueue+WithFuture.swift
Rick Newton-Rogers adfd61adc5 Use Swift 6.0 docs pipeline (#2966)
### Motivation:

Documentation checking catches more issues in Swift 6.0.

### Modifications:

Adopt the Swift 6.0 image and fix the errors.

### Result:

More accurate docs.
2024-11-07 13:03:47 +00:00

51 lines
1.7 KiB
Swift

//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2020 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
#if canImport(Dispatch)
import Dispatch
extension DispatchQueue {
/// Schedules a work item for immediate execution and immediately returns with an `EventLoopFuture` providing the
/// result. For example:
///
/// let futureResult = DispatchQueue.main.asyncWithFuture(eventLoop: myEventLoop) { () -> String in
/// callbackMayBlock()
/// }
/// try let value = futureResult.wait()
///
/// - Parameters:
/// - eventLoop: the `EventLoop` on which to processes the IO / task specified by `callbackMayBlock`.
/// - callbackMayBlock: The scheduled callback for the IO / task.
/// - returns a new `EventLoopFuture<ReturnType>` with value returned by the `block` parameter.
@inlinable
@preconcurrency
public func asyncWithFuture<NewValue: Sendable>(
eventLoop: EventLoop,
_ callbackMayBlock: @escaping @Sendable () throws -> NewValue
) -> EventLoopFuture<NewValue> {
let promise = eventLoop.makePromise(of: NewValue.self)
self.async {
do {
let result = try callbackMayBlock()
promise.succeed(result)
} catch {
promise.fail(error)
}
}
return promise.futureResult
}
}
#endif