简体   繁体   English

for循环中的Swift异步/等待

[英]Swift async/await in for loop

I am scratching my head on new async/await pattern in Swift 5.5 announced in WWDC 2021 and there seems to be lot of learning involved and not as easy to grasp as is pretended to be.我对 WWDC 2021 宣布的 Swift 5.5 中的新 async/await 模式摸不着头脑,似乎涉及很多学习内容,并不像假装那么容易掌握。 I just saw this for loop for instance in WWDC video:我刚刚在 WWDC 视频中看到了这个 for 循环:

    for await id in staticImageIDsURL.lines {

        let thumbnail = await fetchThumbnail(for: id)
        collage.add(thumbnail)
    }

    let result = await collage.draw()

As I understand, every iteration of for loop will suspend the for loop till fetchThumbnail() finishes running (probably on a different thread).据我了解, for 循环的每次迭代都会暂停for 循环,直到 fetchThumbnail() 完成运行(可能在不同的线程上)。 My questions:我的问题:

  1. What is the objective of await id in the for loop line?for 循环行中await id的目的是什么? What if we have the for loop written as following without await?如果我们在没有 await 的情况下编写如下 for 循环会怎样?

     for id in staticImageIDsURL.lines { }
  2. Does the for loop above always ensures that images are added to collage in sequential manner and not in random order depending on which thumbnails are fetched early?上面的for 循环是否总是确保图像以顺序方式添加到拼贴中,而不是根据提前获取的缩​​略图以随机顺序添加? Because in classic completion handler way of writing code, ensuring sequential order in array requires some more logic to the code.因为在编写代码的经典完成处理程序方式中,确保数组中的顺序需要对代码进行更多的逻辑处理。

The await id means geting an id element from the staticImageIDsURL.lines is an asynchronous operation in itself. await id意味着从staticImageIDsURL.lines一个id元素本身就是一个异步操作。

for await id in staticImageIDsURL.lines

This operation has to complete before we enter for loop's body for that iteration.这个操作必须在我们进入该迭代的 for 循环体之前完成。 You should read AsyncSequence docs to know more on this OR can watch Meet AsyncSequence WWDC 2021 session.您应该阅读AsyncSequence文档以了解有关此的更多信息,或者可以观看Meet AsyncSequence WWDC 2021会议。


For each iteration, you are waiting for current operation to complete when you say this.对于每次迭代,当您说这句话时,您都在等待当前操作完成。

let thumbnail = await fetchThumbnail(for: id)

This line will suspend the function each time a new fetch call is initiated, so these thumbnails calls are guaranteed to be completed sequentially.每次启动新的 fetch 调用时,这一行都会暂停该函数,因此这些缩略图调用可以保证按顺序完成。 These calls NEVER happen in parallel, first has to complete before second one is initiated.这些调用永远不会并行发生,第一个调用必须在启动第二个调用之前完成。

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

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