蒸气3:使用wait()时检测到Eventloop错误

时间:2019-02-26 21:25:10

标签: swift future event-loop vapor vapor-fluent

我正在努力了解如何对获取的对象执行批量保存并将其存储到数据库中。将对象存储到数据库后,我想返回查询结果。 我不知道如何使用EventLoopF​​uture进行此操作,因为调用.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,但是如果我调用mapflatMap,则需要依次返回EventLoopFuture<U>U Flight),我对此完全不感兴趣。

我想调用self.storeOrUpdateFlightRecord并忽略结果。我该怎么办?

1 个答案:

答案 0 :(得分:7)

是的,您不能在.wait()上使用eventLoop

您可以使用flatten进行批处理操作

/// Flatten works on array of Future<Void>
return flights.map {
    try self.storeOrUpdateFlightRecord($0, airport: airport, on: conn)
        /// so transform a result of a future to Void
        .transform(to: ())
}
/// then run flatten, it will return Future<Void> as well
.flatten(on: conn).flatMap {
    /// then do what you want :)
    return completion()
}