2025-02-07 10:14:56
,某些文章具有时效性,若有错误或已失效,请在下方留言。Swift lets us perform async operations using both await
and async let
, but although they both run some async code they don’t quite run the same: await
waits for the work to complete so we can read its result, whereas async let
does not.
Swift 允许我们使用 await
和 async let
来执行异步作,但是尽管它们都运行一些异步代码,但它们的运行方式并不完全相同:await
等待工作完成,以便我们可以读取其结果,而 async let
则不会。
Which you choose depends on the kind of work you’re trying to do. For example, if you want to make two network requests where one relates to the other, you might have code like this:
选择哪种方式取决于您要尝试做的工作类型。例如,如果要发出两个网络请求,其中一个请求与另一个请求相关,则可能有如下代码:
func fetchData() async -> Data? {
// do work here
nil
}
func process(_ data: Data?) async -> Bool {
true
}
let download = await fetchData()
let result = await process(download)
There the call to process()
cannot start until the call to fetchData()
has completed and returned its value – it just doesn’t make sense for those two to run simultaneously.
在对 fetchData()
的调用完成并返回其值之前,对 process()
的调用无法开始 – 这两者同时运行是没有意义的。
On the other hand, if you’re making several completely different requests – perhaps you want to download the latest news, the weather forecast, and check whether an app update was available – then those things do not rely on each other to complete and would be great candidates for async let
:
另一方面,如果你正在发出几个完全不同的请求 – 也许你想下载最新消息、天气预报,并检查是否有可用的应用程序更新 – 那么这些事情 不 依赖彼此完成,将是异步 let
的绝佳候选者:
func getNews() async -> [String] { [] }
func getWeather() async -> [String] { [] }
func getUpdateAvailable() async -> Bool { true }
func getAppData() async -> ([String], [String], Bool) {
async let news = getNews()
async let weather = getWeather()
async let hasUpdate = getUpdateAvailable()
return await (news, weather, hasUpdate)
}
So, use await
when it’s important you have a value before continuing, and async let
when your work can continue without the value for the time being – you can always use await
later on when it’s actually needed.
因此,当在继续之前有一个值很重要时,请使用 await
,当你的工作可以暂时在没有值的情况下继续时,使用 async let
—— 你总是可以在以后真正需要的时候使用 await
。
In all these things, remember that “great candidates for async let
” doesn’t mean “this should definitely use async let
.” For example, will making multiple simultaneous requests clog up your user’s network session? If you’re showing information incrementally – i.e., if you use the result of each network request as soon as it finishes – then running multiple requests at the same time might make each one complete more slowly.
在所有这些事情中,请记住,“非常适合async let
”并不意味着“这绝对应该使用 async let
”。例如,同时发出多个请求是否会阻塞用户的网络会话?如果您以增量方式显示信息(即,如果您在每个网络请求完成后立即使用其结果),则同时运行多个请求可能会使每个请求的完成速度变慢。
Similarly, do any of the requests you’re making take time to execute on the server? If so, firing off lots of requests is likely to work well because they can all happen in parallel, particularly if they are going to different servers.
同样,您发出的任何请求是否需要时间才能在服务器上执行?如果是这样,触发大量请求可能会很好地工作,因为它们都可以并行发生,特别是当它们发送到不同的服务器时。
暂无评论内容