[swift-evolution] Two thoughts on concurrency

Yuta Koshizawa koher at koherent.org
Thu Aug 24 20:22:40 CDT 2017


Hi,

Although `throws` and `async` are similar to return a `Result` and a
`Future` respectively as you say, However, `try` and `await` are
corresponding to `flatMap` theoretically.

// `throws/try`
func foo() throws -> Int { ... }

func bar() throws -> Int {
  let a: Int = try foo()
  let b: Int = try foo()
  return a + b
}

// `Result`
func foo() -> Result<Int> { ... }

func bar() -> Result<Int> {
  return foo().flatMap { a: Int in
    foo().flatMap { b: Int in
      return a + b
    }
  }
}

// `async/await`
func foo() async -> Int { ... }

func bar() async -> Int {
  let a: Int = await foo()
  let b: Int = await foo()
  return a + b
}

// `Future`
// `flatMap` works like `then` of JS's `Promise`
// I have an implementation of such `Promise` in Swift
// https://github.com/koher/PromiseK/tree/dev-3.0
func foo() -> Future<Int> { ... }

func bar() -> Future<Int> {
  return foo().flatMap { a: Int in
    foo().flatMap { b: Int in
      return a + b
    }
  }
}

Also, thinking about something like `do/catch` for `async/await`, I
think `do` for blocking is consistent because it should be possible to
return a value from inside `do {}` as well as `do/catch`. For example:

// `throws/try`
func bar() -> Int {
  do {
    return try foo()
  } catch {
    ...
  }
}

// `async/await`
func bar() -> Int {
  do {
    return await foo()
  } block
}

--
Yuta


More information about the swift-evolution mailing list