How to wait for multiple futures to complete in Vapor Swift?
我试图弄清楚如何等待多个期货完成。
我知道如何异步等待他们:
1 2 3 4 5 6 7 8 9 10 11 | let summaryFuture = client.post(summaryURL) { post in post.http.headers.add(name:"authtoken", value: token) }.flatMap(to: SummaryModel.self) { (response) in return try response.content.decode(SummaryModel.self) } let sponsorEnrollerFuture = client.post(sponsporEnroller) { post in post.http.headers.add(name:"authtoken", value: token) }.flatMap(to: SponsorEnrollerModel.self) { (response) in return try response.content.decode(SponsorEnrollerModel.self) } |
你可以使用
对于
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | let summaryFuture = client.post(summaryURL) { post in post.http.headers.add(name:"authtoken", value: token) }.flatMap(to: SummaryModel.self) { (response) in return try response.content.decode(SummaryModel.self) } let sponsorEnrollerFuture = client.post(sponsporEnroller) { post in post.http.headers.add(name:"authtoken", value: token) }.flatMap(to: SponsorEnrollerModel.self) { (response) in return try response.content.decode(SponsorEnrollerModel.self) } // Now combine the two futures return summaryFuture.and(sponsorEnrollerFuture).map { summary, sponsorEnrolled in print("summary: \\(summary)") print("sponsorEnrolled: \\(sponsorEnrolled)") } |
好的。我想到了。
要等待多个 Futures 完成,您必须使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | let summaryFuture = client.post(summaryURL) { post in post.http.headers.add(name:"authtoken", value: token) }.flatMap(to: SummaryModel.self) { (response) in return try response.content.decode(SummaryModel.self) } let sponsorEnrollerFuture = client.post(sponsporEnroller) { post in post.http.headers.add(name:"authtoken", value: token) }.flatMap(to: SponsorEnrollerModel.self) { (response) in return try response.content.decode(SponsorEnrollerModel.self) } // Now combine the two futures let multipleFutures = summaryFuture.add(sponsorEnrollerFuture) // Now I can use mutipleFutures.whenSuccess = {(summary, sponsorEnroller) in ...} |