Home > Blockchain >  Parallel async execution in swift loop
Parallel async execution in swift loop

Time:11-09

I have swift code that looks like this:

var jsFriendlyFreinds = [JSObject]()
for friend in friends {
  let jsFriend = await FriendsPlugin.createFriendResult(friend)
  jsFriendlyFreinds.append(jsFriend)
}

I'd like for all the async calls to happen at the same time, like how javascript's Promise.all works. For one-offs I know you can use async let, but I'm not sure how to do this in the context of a loop or map. Thanks!

CodePudding user response:

You can use the async keyword in your for statement, like

for friend in friends async throws {

CodePudding user response:

You could try this approach, using await withTaskGroup(...), as shown in this example code, to make all the async calls happen in parallel.

let friends: [String] = ["friend-1","friend-2","friend-3"]
var jsFriendlyFreinds = [GoodFriend]()

func getFriends() async {
    // get all friends in parallel
    return await withTaskGroup(of: GoodFriend.self) { group -> Void in
        for friend in friends {
            group.addTask { await createFriendResult(friend) }
        }
        for await value in group {
            jsFriendlyFreinds.append(value)
        }
    }
}

// for testing
func createFriendResult(_ friend: String) async -> GoodFriend {
    // ....
    return GoodFriend(name: "xxx")
}

struct GoodFriend {
   var name: String
   // ....
}

Use it like this:

await getFriends()
  • Related