【发布时间】:2021-09-22 23:17:22
【问题描述】:
我是 Swift 新手,来自 JS,我已经开始构建一个 iOS 应用。
最初,我使用 Promise Kit 来处理异步内容,因为对我来说这比我读到的其他内容更容易。
不管怎样,在 JS 中,我经常使用以下模式:
async function doAyncFunction(item) {
try {
// do async call to fetch data using item
return Promise.resolve(data);
} catch (error) {
return Promise.reject(error);
}
}
const promises = items.map((item) => doAyncFunction(item));
const results = await Promise.all(promises);
我最终通过 Promise Kit 实现了这个功能:
func doManyAsyncRequests(userIds: [String], accessToken: String) -> Promise<Void> {
Promise { seal in
let promises = spotifyUserIds.map {
doSingleAsyncRequest(userId: $0.id, accessToken: accessToken) // this function returns a promise
}
when(fulfilled: promises).done { results in
print("Results: \(results)")
// process results
}.catch { error in
print("\(error)")
// handle error
}
}
}
Promise Kit 的 when 与 JavaScript 的 Promise.all() 相似之处在于,一旦实现了 Promise,就会触发事情在代码中继续进行。
由于我的学习曲线够慢,我决定开始为 iOS 15 编写代码并使用 Swift async/await。
问题:什么 Swift async/await 模式可以执行上述操作,类似于 Promise Kit 的 wait 和 JavaScript 的 Promise.all()?
谢谢。
更新:感谢@workingdog,他帮助我找到了以下解决方案。我现在必须处理错误处理,但现在这是另一个主题。
func getAllThings(users: [User], accessToken: String) async -> [Thing] {
var allThings: [Thing] = []
await withTaskGroup(of: [Thing].self) { group in
for user in users {
group.async {
let userThings = await self.getUsersThings(
accessToken: accessToken,
displayName: user.displayName,
userId: user.id
)
return userThings
}
}
for await (userThings) in group {
allThings = allThings + userThings
}
}
return allThings
}
【问题讨论】:
标签: swift promisekit ios15 swift5.5