简体   繁体   中英

Scala Async and Await Restrictions

I have a code block like this:

val await1: List[Int] = await(futureMethod(id))

val mapped = await1.map(entry => {
  (pq.id, await(anotherFutureMethod(entry.id)))
})

This fails because of "await must not be used under a nested function" How could I get around this? Why should this be a problem?

I had to guess the signatures of your functions, but an example could look like this:

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)
}

Using Future.sequence could be a possible, non-blocking solution to avoid using nested await calls.

You'll want to chain the future calls, not block for them. Blocking futures defies the purpose of a future.

val future1: Future[List[Int]] = futureMethod(id)

val mapped = future1.map(_.flatMap(anotherFutureMethod)
  .map(entry => {
    (pq.id, entry.id)
  }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM