简体   繁体   English

如何在 swift 中使用异步/等待同时运行多个 API 调用?

[英]How to run multiple API call simultaneously using async/await in swift?

As per the new Structured Concurrency in Swift, we can await a API call which is done in an async context, But I want to make multiple API calls simultaneously, for example,根据 Swift 中的新结构化并发,我们可以等待在异步上下文中完成的 API 调用,但我想同时进行多个 API 调用,例如,

profileData = await viewModel.getProfileData()
userCardData = await viewModel.getCardDetails()

The problem in the above case is CardDetails is fetched only after fetching the profile data.上述情况的问题是 CardDetails 仅在获取配置文件数据后才获取。

It can be achieved using the async let .可以使用async let来实现。 This special syntax allows you to group several asynchronous calls and await them together, Example,这种特殊语法允许您将多个异步调用分组并一起等待它们,例如,

async let profileData = viewModel.getProfileData()
async let userCardData = viewModel.getCardDetails()

The above statement indicated that profileData and userCardData , will be available at some point of time in future, just like a promise.上述声明表明profileDatauserCardData将在未来某个时间点可用,就像 promise 一样。

Now in order to use profileData and userCardData we need to use await, incase the data is fetched and available it would return immediately, or it suspend until the data is available.现在为了使用 profileData 和 userCardData,我们需要使用 await,以防数据被获取并且可用,它会立即返回,或者暂停直到数据可用。

The value from the above request can be used like,来自上述请求的值可以像这样使用,

let (fetchedProfileData, fetchedUserCardData) = try await (profileData, userCardData)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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