Scala异步和等待限制
我有这样一个代码块:Scala异步和等待限制,scala,asynchronous,Scala,Asynchronous,我有这样一个代码块: val await1: List[Int] = await(futureMethod(id)) val mapped = await1.map(entry => { (pq.id, await(anotherFutureMethod(entry.id))) }) def futureMethod(id: Int): Future[List[Int]] = Future.successful(0 to id toList) def anotherFutureMe
val await1: List[Int] = await(futureMethod(id))
val mapped = await1.map(entry => {
(pq.id, await(anotherFutureMethod(entry.id)))
})
def futureMethod(id: Int): Future[List[Int]] = Future.successful(0 to id toList)
def anotherFutureMethod(id: Int): Future[String] = Future.successful(id.toString)
def finalFuture(id: Int) = async {
val await1 = await(futureMethod(id))
val mapped = Future.sequence(await1 map anotherFutureMethod)
await(mapped)
}
由于“不能在嵌套函数下使用wait”而导致此操作失败,我该如何解决此问题?为什么这会是一个问题?您将希望链接未来的调用,而不是阻止它们。舞台调度 未来违背了未来的目的
val future1: Future[List[Int]] = futureMethod(id)
val mapped = future1.map(_.flatMap(anotherFutureMethod)
.map(entry => {
(pq.id, entry.id)
}))
您将希望链接未来的呼叫,而不是阻止它们。舞台调度 未来违背了未来的目的
val future1: Future[List[Int]] = futureMethod(id)
val mapped = future1.map(_.flatMap(anotherFutureMethod)
.map(entry => {
(pq.id, entry.id)
}))
我不得不猜测函数的签名,但示例可能如下所示:
val await1: List[Int] = await(futureMethod(id))
val mapped = await1.map(entry => {
(pq.id, await(anotherFutureMethod(entry.id)))
})
def futureMethod(id: Int): Future[List[Int]] = Future.successful(0 to id toList)
def anotherFutureMethod(id: Int): Future[String] = Future.successful(id.toString)
def finalFuture(id: Int) = async {
val await1 = await(futureMethod(id))
val mapped = Future.sequence(await1 map anotherFutureMethod)
await(mapped)
}
使用
Future.sequence
可能是一种可能的非阻塞解决方案,以避免使用嵌套的wait
调用。我不得不猜测函数的签名,但示例可能如下所示:
val await1: List[Int] = await(futureMethod(id))
val mapped = await1.map(entry => {
(pq.id, await(anotherFutureMethod(entry.id)))
})
def futureMethod(id: Int): Future[List[Int]] = Future.successful(0 to id toList)
def anotherFutureMethod(id: Int): Future[String] = Future.successful(id.toString)
def finalFuture(id: Int) = async {
val await1 = await(futureMethod(id))
val mapped = Future.sequence(await1 map anotherFutureMethod)
await(mapped)
}
使用
Future.sequence
可能是避免使用嵌套的await
调用的一种可能的非阻塞解决方案。await from async/await实际上不阻塞,async是@dk14 oh neat宏,我不知道该库。await from async/await实际上不阻塞,async是@dk14 oh neat宏,我不知道那个图书馆。这个问题本身在上有一些解决方法的描述。其中一种方法是在async之上编写一个层,通过高阶函数提升wait。我最近在scala gopher[](下一个版本,现在您必须从源代码处编译master才能使用此功能)中实现了此功能。在中描述了问题本身,并介绍了一些解决方法。其中一种方法是在async之上编写一个层,通过高阶函数提升wait。我最近在scala gopher[]中实现了这一点(下一个版本,现在您必须从源代码编译master才能使用此功能)