因此,我试图在我的Vapor端点之一中调用第二个端点。我有一个端点,只是一个不错的选择,而且运作良好:
router.get("status") { req -> Future<ConnectionResponse> in
let client = try req.make(Client.self)
let response = client.get("https://url.com/endpoint/")
return response.flatMap(to: ConnectionResponse.self, { response in
return try response.content.decode(ConnectionResponse.self)
})
}
这将正确返回ConnectionResponse json。当我尝试执行相同的操作时,但是在需要一些参数的POST中,我无法弄清楚为什么编译器不允许我运行:
router.post("purchase") { req -> Future<ConnectionResponse> in
return try req.content.decode(PurchaseRequest.self).map(to: ConnectionResponse.self, { response in
let client = try req.make(Client.self)
let response = client.get("https://url.com/endpoint/")
return response.flatMap(to: ConnectionResponse.self, { response in
return try response.content.decode(ConnectionResponse.self)
})
})
}
flatMap
说Cannot convert return expression of type 'EventLoopFuture<ConnectionResponse>' to return type 'ConnectionResponse'
失败。
如您所见,除了对POST参数进行初始解码之外,purchase
GET调用与status
相同。我究竟做错了什么?
答案 0 :(得分:3)
只需替换
return try req.content.decode(PurchaseRequest.self).map(to: ConnectionResponse.self, { response in
使用
return try req.content.decode(PurchaseRequest.self).flatMap(to: ConnectionResponse.self, { response in
完整的工作代码可能看起来像这样
router.post("purchase") { req -> Future<ConnectionResponse> in
return try req.content.decode(PurchaseRequest.self).flatMap { response in
let client = try req.make(Client.self)
let response = client.get("https://url.com/endpoint/")
return response.flatMap { response in
return try response.content.decode(ConnectionResponse.self)
}
}
}
那么map
和flatMap
有什么区别?
flatMap
,则使用 Future<Something>
,例如:
someDatabaseCall(on: container).flatMap { databaseResult1 in
/// it will return Future<DatabaseResult>
/// that's why we use `flatMap` above instead of `map`
return anotherDatabaseCall(on: container)
}
map
用于非预期结果,例如:
someDatabaseCall(on: container).map { databaseResult1 in
/// it will return non-future result
/// that's we use `map` above instead of `flatMap`
return "hello world" // just simple string
}
什么是Future<>
?只是一个承诺,就像带有回调的对象一样。