关于 xcode:如何在 Vapor Swift 中等待多个期货完成?

How to wait for multiple futures to complete in Vapor Swift?

我试图弄清楚如何等待多个期货完成。
我知道如何异步等待他们:
summaryFuture.whenSuccess {} 但这只处理一种情况。我需要等待summaryFuture 和sponsorFuture 完成,然后在发回响应之前同时处理两者。

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)
    }

你可以使用 .and.flatten

对于 .flatten,您的期货应该返回 Void,因此最终结果也将是 Future<Void>

.and 可以这样使用

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 完成,您必须使用 .add。在我的特殊情况下。

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 ...}