vine
(vine)
1
- 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
tonyarnold
(Tony Arnold)
2
I believe you'd express that as:
let a = try await futureA.get()
let b = try await futureB.get()
vine
(vine)
3
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()
tonyarnold
(Tony Arnold)
4
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.
vine
(vine)
5
Which one is closer to the old code?
+ futureA.and(futureB).flatMap { (a, b) in
// Do something with a and b.
}
tonyarnold
(Tony Arnold)
6
The first example I posted:
let a = try await futureA.get()
let b = try await futureB.get()
0xTim
(Tim)
8
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
// ...
}
}
11 Likes
tonyarnold
(Tony Arnold)
9
TIL - I thought that the and(…) method ran the futures serially. Thanks for clearing that up, Tim!