- flatMap(futureA, futureB) { a, b in
+ futureA.and(futureB).flatMap { (a, b) in
// Do something with a and b.
}
How to convert to async/await
- flatMap(futureA, futureB) { a, b in
+ futureA.and(futureB).flatMap { (a, b) in
// Do something with a and b.
}
How to convert to async/await
I believe you'd express that as:
let a = try await futureA.get()
let b = try await futureB.get()
Is there any difference between them? Which one should I use?
async let a = try futureA.get()
async let b = try futureB.get()
let result = await [a, b]
or
let a = try await futureA.get()
let b = try await futureB.get()
I believe that the first two (async let
) will execute the futures concurrently.
The one I provided mimics the original behaviour of the flat mapped futures and execute them serially (one after the other).
I can't really recommend which option you should choose without a bit more context of what you're attempting to do.
Which one is closer to the old code?
+ futureA.and(futureB).flatMap { (a, b) in
// Do something with a and b.
}
The first example I posted:
let a = try await futureA.get()
let b = try await futureB.get()
OK, thanks
Just to clarify, since futures are 'hot' in NIO land
futureA.and(futureB).flatMap { (a, b) in
// Do something with a and b.
}
is the equivalent to
async let a = try futureA.get()
async let b = try futureB.get()
let result = await [a, b]
As the futures are started as soon as you create them. The equivalent of
let a = try await futureA.get()
let b = try await futureB.get()
Would be
return someFunctionThatReturnsFutureA().flatMap { a in
someFunctionThatReturnsFutureB().flatMap { b in
// ...
}
}
TIL - I thought that the and(…)
method ran the futures serially. Thanks for clearing that up, Tim!