我正在努力理解如何批量保存获取的对象并将它们存储到数据库中。将对象存储到数据库后,我想返回查询结果。我无法理解如何使用 EventLoopFuture 执行此操作,因为当我打电话时.wait()
收到错误消息:
前提条件失败:检测到错误:在 EventLoop 上时不得调用 wait()。
作为我的问题的一个例子:
- 我需要从外部端点获取一个实体(比如说机场的航班)
- 该调用的结果需要保存到数据库中。如果航班存在于数据库中,则需要更新,否则创建。
- 完成后,需要返回数据库中所有航班的列表。
这是我到目前为止得到的,但这给了我一个错误:
func flights(on conn: DatabaseConnectable, customerName: String, flightType: FlightType) throws -> Future<[Flight]> {
return Airport.query(on: conn).filter(\.customerName == customerName).first().flatMap(to: [Flight].self) { airport in
guard let airport = airport else {
throw Abort(.notFound)
}
guard let airportId = airport.id else {
throw Abort(.internalServerError)
}
// Update items for customer
let fetcher: AirportManaging?
switch customerName.lowercased() {
case "coolCustomer":
fetcher = StoreOneFetcher()
default:
fetcher = nil
debugPrint("Unhandled customer to fetch from!")
// Do nothing
}
let completion = Flight.query(on: conn).filter(\.airportId == airportId).filter(\.flightType == flightType).all
guard let flightFetcher = fetcher else { // No customer fetcher to get from, but still return whats in the DB
return completion()
}
return try flightFetcher.fetchDataForAirport(customerName, on: conn).then({ (flights) -> EventLoopFuture<[Flight]> in
flights.forEach { flight in
_ = try? self.storeOrUpdateFlightRecord(flight, airport: airport, on: conn).wait()
}
return completion()
})
}
}
func storeOrUpdateFlightRecord(_ flight: FetcherFlight, airport: Airport, on conn: DatabaseConnectable) throws -> EventLoopFuture<Flight> {
guard let airportId = airport.id else {
throw Abort(.internalServerError)
}
return Flight.query(on: conn).filter(\.itemName == flight.itemName).filter(\.airportId == airportId).filter(\.flightType == flight.type).all().flatMap(to: Flight.self) { flights in
if let firstFlight = flights.first {
debugPrint("Found flight in database, updating...")
return flight.toFlight(forAirport: airport).save(on: conn)
}
debugPrint("Did not find flight, saving new...")
return flight.toFlight(forAirport: airport).save(on: conn)
}
}
所以问题就在网上_ = try? self.storeOrUpdateFlightRecord(flight, airport: airport, on: conn).wait()
。我不能打电话wait()
,因为它会阻止 eventLoop,但是如果我打电话map
或者flatMap
我需要反过来返回一个EventLoopFuture<U>
( U
being Flight
),我对此完全不感兴趣。
我想self.storeOrUpdateFlightRecord
被叫到结果被忽略。我怎样才能做到这一点?