通过异步函数循环构建快速数组

问题描述 投票:0回答:1

你好, 我必须循环遍历对象数组并对每个项目执行操作,其中异步返回结果。我对 Swift 中的 async/await 编码风格非常陌生,不知道如何找到更简单的解决方案。感谢任何帮助。请找到下面的示例代码。我尝试将其包围在

Task
内,但由于编译器错误,它不起作用。


func performOperation(ids: [UUID]) -> [TypeA] {

var output: [TypeA] = []

for id in ids { 
  Task {
    let results = await someAsyncFunction(id)
    output.append(contendsOf: results)  // Does not compile.
  }
}

return output

}

func someAsyncFunction(id: UUID) async -> [TypeA] {
 // third party framework function.
}


swift async-await task
1个回答
0
投票

一般不建议同步等待异步任务,因此一旦调用堆栈中存在异步被调用者,就必须将所有调用者修改为异步,直到不需要返回值的调用者为止。

func performOperation(ids: [UUID]) async -> [TypeA]  {
    var output: [TypeA] = []
    for id in ids {
        let results = await someAsyncFunction(id)
        output.append(contentsOf: results)  // Does not compile.
    }
    return output
}

func main(){
    Task{
        let output = performOperation(ids: ids)
    }
}

© www.soinside.com 2019 - 2024. All rights reserved.