WWDC 2021: Intro to async/await | raywenderlich.com

With WWDC 2021, Apple released a whole bunch of concurrency features with async/await leading the pack. In this video, you'll learn how to use this new language feature but more importantly, you'll learn how it fits into Apple's concurrency landscape.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/25008723-wwdc-2021-intro-to-async-await
1 Like

I have a question regarding async and the MainActor. It this code I expect whats within the async to run in the background, except for whats in the MainActor. But as you can see once the MainActor has run the rest of the code within the async block also runs on the main thread.

async(priority:.background)
{
    await MainActor.run
    {
        print("MainActor: Is main operation queue = \(OperationQueue.current == OperationQueue.main)")
        print("MainActor: isMainThread = \(Thread.isMainThread)")
    }

    print("This will always run after the above code.")

    print("Background: Is main operation queue = \(OperationQueue.current == OperationQueue.main)")
    print("Background: isMainThread = \(Thread.isMainThread)")
}

Console Log:

MainActor: Is main operation queue = true
MainActor: isMainThread = true
This will always run after the above code.
Background: Is main operation queue = true
Background: isMainThread = true

Hi,
I’m trying to reuse some async marked code that works great in a SwiftUI application in a simple Swift-Command line tool.
Lets assume for simplicity that I’d like to reuse a function

func fetchData(base : String) async throws -> SomeDate
    {
        let request = createURLRequest(forBase: base)
        
        let (data, response) = try await URLSession.shared.data(for: request)
        guard (response as? HTTPURLResponse)?.statusCode == 200 else {
            throw FetchError.urlResponse
        }
        let returnData = try! JSONDecoder().decode(SomeData.self, from: data)
        
        return returnData
    }

in my command.
A call like

    let allInfo = try clerk.fetchData("base")

in my “main-function” gives the error message 'async' call in a function that does not support concurrency.
What is the correct way to handle this case.

Thanks
Peter

Hi Peter, this the comments for a beta release of async/await. Your best bet to get this answered is to post it in a more general forum. Feel free to check out discord. Good luck!