[英]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?有没有一种方法可以使用两种不同类型的async let语法执行异步操作,以便这两种方法并行运行?
I've tried with the TaskGroup as well but can't figure this out我也尝试过TaskGroup但无法弄清楚
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
.或者,如果您正在等待的任何事情也需要
try
,请将其放在相应的await
之前。 For instance if both of them requires try
, you would say例如,如果他们都需要
try
,你会说
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.现在 result 是表示返回值的两个值的元组——result.0 是
options
值, result.0
是variants
值result.1
And the important thing is that result
has no value until both async let
values have returned — in parallel.重要的是
result
在两个async let
值都返回之前没有任何价值——并行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.