简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM