Skip to content

Instantly share code, notes, and snippets.

@alfianlosari
Created May 31, 2021 07:31
Show Gist options
  • Save alfianlosari/99f64a1d292ca973805fd4d62cc924fc to your computer and use it in GitHub Desktop.
Save alfianlosari/99f64a1d292ca973805fd4d62cc924fc to your computer and use it in GitHub Desktop.
Creating Single Async Task
// 1
func fetchAPI<D: Decodable>(url: URL) async throws -> D {
// 2
let task = Task { () -> D in
// 3
let data = try Data(contentsOf: url)
let decodedData = try JSONDecoder().decode(D.self, from: data)
return decodedData
}
// 4
return try await task.value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment