qweruiop
qweruiop

Reputation: 3266

What are the semantics of Future::then?

I’m confused by the semantics of the combinator then.

Intuitively, a.then(|r| f(r)) is a future that when a finishes with r, resolves to f(r). In other words, composing f after a. E.g. a reads a number from I/O and f doubles it. This makes sense and that’s been my mental model.

Digging deeper, in fact there’s more than that. The closure passed to then yields a IntoFuture, which means applying f to the result of a returns another future. The above understanding is incorrect then as f(r) is still not fully resolved.

From what I read in the documentation and the source code, it seems to be the following: a.then(|r| f(r)) essentially keeps polling until the future a is resolved, then keep polling f(r) (which is also a future) until it resolves. Finally the whole thing is resolved.

Is this the right way to think about it? Why do we need a second layer of futures?

Upvotes: 1

Views: 99

Answers (1)

Boiethios
Boiethios

Reputation: 42819

then does not wait for the future to be finished. It is lazy, as said by the doc:

The closure is only run after successful completion of the self future.

It basically chains 2 futures. Suppose you have:

  • one future future_a that "computes" a a,
  • one method foo that takes an a and returns a future_b.
future_a.then(foo)

will be a future that merge those 2 futures to return a future_b

Upvotes: 3

Related Questions