@@ -217,3 +217,51 @@ final public class DataLoader<Key: Hashable, Value> {
217
217
}
218
218
}
219
219
}
220
+
221
+ #if compiler(>=5.5) && canImport(_Concurrency)
222
+
223
+ /// Batch load function using async await
224
+ public typealias ConcurrentBatchLoadFunction < Key, Value> = @Sendable ( _ keys: [ Key ] ) async throws -> [ DataLoaderFutureValue < Value > ]
225
+
226
+ public extension DataLoader {
227
+ @available ( macOS 12 , iOS 15 , watchOS 8 , tvOS 15 , * )
228
+ convenience init (
229
+ on eventLoop: EventLoop ,
230
+ options: DataLoaderOptions < Key , Value > = DataLoaderOptions ( ) ,
231
+ throwing asyncThrowingLoadFunction: @escaping ConcurrentBatchLoadFunction < Key , Value >
232
+ ) {
233
+ self . init ( options: options, batchLoadFunction: { keys in
234
+ let promise = eventLoop. next ( ) . makePromise ( of: [ DataLoaderFutureValue < Value > ] . self)
235
+ promise. completeWithTask {
236
+ try await asyncThrowingLoadFunction ( keys)
237
+ }
238
+ return promise. futureResult
239
+ } )
240
+ }
241
+
242
+ /// Asynchronously loads a key, returning the value represented by that key.
243
+ @available ( macOS 12 , iOS 15 , watchOS 8 , tvOS 15 , * )
244
+ func load( key: Key , on eventLoopGroup: EventLoopGroup ) async throws -> Value {
245
+ try await load ( key: key, on: eventLoopGroup) . get ( )
246
+ }
247
+
248
+ /// Asynchronously loads multiple keys, promising an array of values:
249
+ ///
250
+ /// ```
251
+ /// let aAndB = try await myLoader.loadMany(keys: [ "a", "b" ], on: eventLoopGroup)
252
+ /// ```
253
+ ///
254
+ /// This is equivalent to the more verbose:
255
+ ///
256
+ /// ```
257
+ /// async let a = myLoader.load(key: "a", on: eventLoopGroup)
258
+ /// async let b = myLoader.load(key: "b", on: eventLoopGroup)
259
+ /// let aAndB = try await a + b
260
+ /// ```
261
+ @available ( macOS 12 , iOS 15 , watchOS 8 , tvOS 15 , * )
262
+ func loadMany( keys: [ Key ] , on eventLoopGroup: EventLoopGroup ) async throws -> [ Value ] {
263
+ try await loadMany ( keys: keys, on: eventLoopGroup) . get ( )
264
+ }
265
+ }
266
+
267
+ #endif
0 commit comments