Stephane Maarek
Stephane Maarek

Reputation: 5352

Scala: from Seq to Sequential Futures

I have a Seq of Book that I need to save to my database in the same order they are in the Seq. Book.save returns a Future[Unit]

If I write the following code, I know the save order may not be preserved:

books.map(_.save)

How can I sequentially execute these saves, but return the result as a Future? Thanks!

Upvotes: 4

Views: 134

Answers (1)

Nyavro
Nyavro

Reputation: 8866

You can use foldLeft:

val res:Future[Unit] = books.foldLeft(Future.successful {}) {
  case (acc, book) => acc.flatMap(_ => book.save)
}

Upvotes: 5

Related Questions