我有4个功能,createUser
,updateUser
,deleteUser
,listUser
。
这4个功能都是被动的。
如何按此顺序执行它们?
createUser->listUser(list created user)->updateUser->listUser(list updated user)>deleteUser->listUser
我的createUser:
def createSomeUser() {
var users = List[BSONDocument]()
val user1 = BSONDocument(
"firstName" -> "Kobe",
"lastName" -> "Bryant",
"Number" -> "8"
)
users = user1 :: users
val enumerator = Enumerator.enumerate(users)
val future = collection.bulkInsert(enumerator)
future.onComplete {
case Failure(e) => throw e
case Success(lastError) => {
println("All users were inserted to DB")
}
}
}
我的updateUser:
def updateAUser(firstName: String, number: Int) {
val selector = BSONDocument("firstName" -> firstName)
val modifier = BSONDocument(
"$set" -> BSONDocument(
"Number" -> number))
val futureUpdate = collection.update(selector, modifier)
//get a future update
futureUpdate.onComplete {
case Failure(e) => throw e
case Success(lastError) => {
println("successfully Update user")
}
}
}
我的deleteUser:
def deleteAUser(firstName: String) {
val selector = BSONDocument(
"firstName" -> firstName)
val futureRemove = collection.remove(selector)
futureRemove.onComplete {
case Failure(e) => throw e
case Success(lasterror) => {
println("successfully removed users")
}
}
}
我的listUser:
def listDocs() = {
// Select all documents
val query = BSONDocument()
// select all fields
val filter = BSONDocument(
"lastName" -> 1,
"firstName" -> 1,
"Number" -> 1,
"_id" -> 1)
val fList = collection.
find(query, filter).
cursor[BSONDocument].
collect[List]()
fList.map { list =>
list.foreach { doc =>
println("found User: " + BSONDocument.pretty(doc))
}
}
}
答案 0 :(得分:4)
您可以使用flatMap
,但您必须稍微更改您的功能实施,因为它们不会返回您可以链接的未来,例如:
def createSomeUser(): Future[SomeType] = {
(omitted for brevity)
collection.bulkInsert(enumerator)
}
def updateAUser(firstName: String, number: Int): Future[SomeType] = {
(omitted for brevity)
collection.update(selector, modifier)
}
def deleteAUser(firstName: String): Future[SomeType] = {
(omitted for brevity)
collection.remove(selector)
}
他们现在都返回了一个有一定价值的未来,现在使用flatMap
你可以链接执行:
createSomeUser().flatMap {
created => updateAUser(someName, someNumber).flatMap {
updatedUser => deleteAUser(created.getName).flatMap {
deleted => // and so on...
}
}
}
在这种情况下修改函数实现似乎是逻辑,如果你不希望你最有可能将它们包装在另一个未来(在被调用时)或者在onComplete
方法中链接函数执行,但是这会对行为进行硬编码,并且无法像我向您展示的那样创建自定义调用链。