`then()` attaches a continuation to a future, scheduling processing for when its result is ready instead of requiring the caller to wait. section 4.4.3
A continuation changes how the result and follow-on work are handled:
- It receives a ready future as its argument. Adding it invalidates the original future and returns a new future for the continuation’s result; execution is on an unspecified thread. section 4.4.3
- Chained continuations can return futures: `then()` unwraps the result, so the chain need not produce nested futures or block between asynchronous operations. section 4.4.4
std::experimental::future<int> find_the_answer; auto fut=find_the_answer(); auto fut2=fut.then(find_the_question); assert(!fut.valid()); assert(fut2.valid());
This short example shows the original future becoming invalid while the future returned by `then()` remains valid. section 4.4.3
Listing 4.20. A function to process user login with continuations
std::experimental::future<void> process_login(
std::string const& username,std::string const& password)
{
return spawn_async([=](){
return backend.authenticate_user(username,password);
}).then([](std::experimental::future<user_id> id){
return backend.request_current_info(id.get());
}).then([](std::experimental::future<user_data> info_to_display){
try{
update_display(info_to_display.get());
} catch(std::exception& e){
display_error(e);
}
});
}
The login flow chains authentication, requesting user data, and updating the display; the fully asynchronous variant is shown separately. section 4.4.4
