在尝试聚合少数方法的结果时,我有这种情况。
我想要做的是获取包含对象列表的对象的Future。
然后我将未来映射到字符串列表 然后我想迭代这个列表
如果可能以异步方式调用几个方法,然后将结果合并到一个对象,我必须等待所有方法完成 并将结果发送到数据库。
这是我卡住的地方......
更新
我现在根据评论中的建议编辑方法我遇到了类型不匹配错误
expected List[postMd.PostMD]....
,
def getComplatePost(url: String): Unit = {
val postMd = new PostMetaData
val com = new Comments
val post = new Post
val fullPost = new CompletePost
val postMdList: Future[List[postMd.PostMD]] = postMd.getPostMetaData(url, "396697410351933") // get the list of id
postMdList.flatMap(x => {
val fromid = x.map(_.fromID) //extract the Future to a list of string
for {
id <- fromid
val c = com.getComments(id)
val p = post.getPost(id)
}yield (c,p)
})
}
感谢 三木
答案 0 :(得分:0)
您可以使用&#39; for - yield&#39;这个案例。 &#39;对于&#39;在每个语句完成后执行yield操作。
这主要是因为&#39; 是一个语法糖,它进一步映射到嵌套的flatMap或map或foreach ......取决于正在执行的操作。
以下是代码中的修改后的代码段:
for {
id <- fromid
//invoke methods
c = com.getComments(id)
p = post.getPost(id)
k = post.getPostLikes(id)
} // merge results and send data to DB