1

该代码使用 ReactiveMongo 向 MongoDB 发送请求并返回Future[BSONDocument],但我的代码处理数据列表,因此我需要获取 的值,Future[BSONDocument]然后将其转换为列表。

我如何在不阻塞的情况下做到这一点?

更新:

我正在使用 ReactiveMongoRawCommand

 def findLByDistance()(implicit ec: ExecutionContext) =  db.command(RawCommand(
        BSONDocument(
            "aggregate" -> collName,
            "pipeline" -> BSONArray(BSONDocument(
                "$geoNear" -> BSONDocument(
                    "near" -> BSONArray(44.72,25.365),
                    "distanceField" -> "location.distance",
                    "maxDistance" -> 0.08,
                    "uniqueDocs" -> true)))
                )))

结果出来了Future[BSONDocument]。对于一些简单的查询,我使用了允许简单转换的默认查询生成器

def findLimitedEvents()(implicit ec: ExecutionContext) =
  collection.find(BSONDocument.empty)
    .query(BSONDocument("tags" -> "lazy"))
    .options(QueryOpts().batchSize(10))
    .cursor.collect[List](10, true)

我基本上需要RawCommand输出类型来匹配以前使用的。

4

2 回答 2

0

不确定您的确切用例(显示更多代码会有所帮助),但将 from 转换List[Future[BSONDocument]]为 one可能会很有用Future[List[BsonDocument]],您可以更轻松地onSuccessmap继续使用,您可以通过以下方式执行此操作:

val futures: List[Future[A]] = List(f1, f2, f3)
val futureOfThose: Future[List[A]] = Future.sequence(futures)
于 2014-02-15T21:14:47.287 回答
-1

没有阻塞就无法“获得”未来。如果你想等待 aFuture完成,那么你必须阻止。

可以做的是map进入Future另一个Future

val futureDoc: Future[BSONDocument] = ...
val futureList = futureDoc map { doc => docToList(doc) }

最终,你会达到一个点,你已经组合、映射、恢复等所有未来,并希望结果发生一些事情。这是您阻止或建立处理程序以对最终结果执行某些操作的地方:

val futureThing: Future[Thing] = ...

//this next bit will be executed at some later time,
//probably on a different thread
futureThing onSuccess {
  case thing => doWhateverWith(thing)
}
于 2014-02-15T20:58:46.187 回答