如何在Vapor Swift中等待多个期货完成?

时间:2019-03-21 16:01:01

标签: swift xcode vapor

我正在尝试弄清楚如何等待多个期货完成。 我知道如何异步等待它们: <Files> <File> <Charges> <charge> <FRNo>99988881111</FRNo> <amount>25.0</amount> <Date>2019-02-25</Date> <chargeType>Recur</chargeType> <phoneNo>4444000012</phoneNo> </charge> <charge> <FRNo>99988881111</FRNo> <amount>40.0</amount> <Date>2019-02-25</Date> <chargeType>Recur</chargeType> <phoneNo>4444000012</phoneNo> </charge> </Charges> <FRNo>99988881111</FRNo> <address>New YORK</address> <amount>111</amount> <DN>100000</DN> <name>Rite</name> <phoneNo>4444000012</phoneNo> <tax>8.0</tax> </File> </Files> ,但这仅能处理一种情况。我需要等待summaryFuture和SponsorFuture都完成,然后在发送回响应之前都使用它们。

summaryFuture.whenSuccess {}

2 个答案:

答案 0 :(得分:2)

您可以使用.and.flatten

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

.and可能会这样使用

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

答案 1 :(得分:0)

好的。我想到了。

要等待多个期货完成,您必须使用.add。在我的情况下。

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