Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to perform two asynchronous operations with async let for two different types? Swift

Is there a way to perform asynchronous operations with the async let syntax for two different types, so that both of those methods are run in parallel?

I’ve tried with the TaskGroup as well but can’t figure this out

    func getOptionsAndVariants() async {
        do {
            async let options: [ProductOption] = NetworkManager.sharedInstance.getProductOptions(product.id.description)
            async let variants: [ProductVariant] = NetworkManager.sharedInstance.getProductVariants(product.id)
            
            await try options, variants // Wrong syntax

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Change

await try options, variants // Wrong syntax

To

let result = (await options, await variants)

Or, if either of the things you are awaiting also requires try, put it before the respective await. For instance if both of them requires try, you would say

let result = (try await options, try await variants)

Now result is a tuple of two values representing the returned values — result.0 is the options value, and result.1 is the variants value.

And the important thing is that result has no value until both async let values have returned — in parallel.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading