carson-katri / carson-katri/swift-request

`async`/`await` support

Open
#63 0 comments 0 reactions 0 assignees View on GitHub
enhancement
Dominant language
Swift
Stars
740
Forks
42
PR merge metrics
No merged PRs in 30d

Description

The basic idea is that you can await any `Request` using `call()`:

```swift
let getTodos = AnyRequest<[Todo]> {
Url("todos.com/api")
}
let todos = try await getTodos.call()
```

`callAsFunction` could also be added to simplify this demo to:
```swift
let todos = try await getTodos()
```

This opens up new opportunities for crafting readable APIs:
```swift
enum API {
// These can be used as async throwing functions:
static let getPosts = AnyRequest<[Post]> {
Url("...")
}
static let getUsers = AnyRequest<[User]> {
Url("...")
}
// Real functions can also be added:
static func getPost(id: Int) async throws -> Post {
try await AnyRequest {
Url(".../\(id)")
}()
}
}

// Simply use these as functions:
let posts = try await API.getPosts()
let users = try await API.getUsers()
let post = try await API.getPost(id: 0)
```

`async let` gives the power of concurrency:
```swift
async let posts = API.getPosts()
async let users = API.getUsers()
let authored = zip(try await callTodos, try await callAsFunctionTodos)
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.