1

List[String] に製品 ID のリストがあります。Mongo から List[JsObject] を返したいと思います。製品 List の要素ごとに 1 つの JsObject です。

1つの製品だけを取得するには、次のものが必要です。

def getIndivProduct(productID: String): Future[List[JsObject]] = {

  val cursor: Cursor[JsObject] = collectionItems.
      find(Json.obj("product-number" -> productID)).
      cursor[JsObject]

  val futureProductList: Future[List[JsObject]] = cursor.collect[List]()

  futureProductList

}

検索して返す文字列のリストを「フィード」するにはどうすればよいですか? この署名で:

 def getProductsFromList(productIDs: List[String]): Future[List[JsObject]] = {

    ???

 }

ありがとう

4

2 に答える 2

0

List-of-Future-of-ListからFuture-of -List への変換関数が必要です

import scala.concurrent._
import ExecutionContext.Implicits.global

def singleFuture[A](futures: List[Future[List[A]]]): Future[List[A]] = {

    val p = Promise[List[A]]()
    p.success(List.empty[A])

    val f = p.future // a future containing empty list.

    futures.foldRight(f) {
        (fut, accum) =>  // foldRight means accumulator is on right.

        for {
            listAccum <- accum; 
            listA  <- fut  
        }
        yield (listA ::: listAccum)   // List[A] ::: List[A]
    }
}

これを考えると、それは簡単です:

def getProductsFromList(productIDs: List[String]): Future[List[JsObject]] = {

    val indivProdList = productIDs.map(getIndivProduct(_))
    singleFuture(indivProdList)

}
于 2014-03-12T15:39:08.257 に答える