Skip to content
This repository has been archived by the owner on Jun 27, 2023. It is now read-only.

Replace Future.flatMap with Future.then? #183

Open
MrMage opened this issue Nov 23, 2018 · 2 comments
Open

Replace Future.flatMap with Future.then? #183

MrMage opened this issue Nov 23, 2018 · 2 comments
Assignees

Comments

@MrMage
Copy link
Contributor

MrMage commented Nov 23, 2018

Currently, Future.flatMap is implemented like this:

public func flatMap<T>(to type: T.Type = T.self, _ callback: @escaping (Expectation) throws -> Future<T>) -> Future<T> {

Would it be possible to call through to SwiftNIO's implementation of Future.then instead?

https://github.com/apple/swift-nio/blob/6f3671de4ed1350b86762e0da317075f69983f7d/Sources/NIO/EventLoopFuture.swift#L437

Let me know if I'm missing something.

@MrMage MrMage assigned MrMage and tanner0101 and unassigned MrMage Nov 23, 2018
@vzsg
Copy link
Member

vzsg commented Nov 23, 2018

It's certainly possible, all you need to mind is that flatMap allows the closure to throw, while then does not.

This should be equivalent to the current implementation:

extension Future {
    func flatmap2<T>(to type: T.Type = T.self, _ callback: @escaping (Expectation) throws -> Future<T>) -> Future<T> {
        return self.then { [eventLoop = self.eventLoop] expectation in
            do {
                return try callback(expectation)
            } catch {
                return eventLoop.newFailedFuture(error: error)
            }
        }
    }
}

@MrMage
Copy link
Contributor Author

MrMage commented Nov 26, 2018

Thanks! I did not spot that then does not take a throwing closure. Leaving this open in case we want to change the implementation, e.g. for Vapor 4 (although this should be a non-breaking change anyway).

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants