Tutorial » Chaining continuables

Explains how to chain multiple continuable_base objects together.

Using then and results

A continuable_base provides various methods to continue the asynchronous call hierarchy. The most important method therefor is continuable_base::then which changes the object through attaching a result handler:

http_request("github.com")
  .then([] (std::string result) {
    // Do something...
  });

A new continuable_base is created which result depends on the return type of the handler. For instance it is possible to return plain values or the next continuable_base to continue the call hierarchy. See continuable_base::then for details.

mysql_query("SELECT `id`, `name` FROM `users`")
  .then([](ResultSet users) {
    // Return the next continuable to process ...
    return mysql_query("SELECT `id` name FROM `sessions`");
  })
  .then([](ResultSet sessions) {
    // ... or pass multiple values to the next callback using tuples or pairs ...
    return std::make_tuple(std::move(sessions), true);
  })
  .then([](ResultSet sessions, bool is_ok) {
    // ... or pass a single value to the next callback ...
    return 10;
  })
  .then([](auto value) {
    //     ^^^^ Templated callbacks are possible too
  })
  // ... you may even pass continuables to the `then` method directly:
  .then(mysql_query("SELECT * FROM `statistics`"))
  .then([](ResultSet result) {
    // ...
  });

Making use of partial argument application

Callbacks passed to then are only called with the amount of arguments that are accepted.

(http_request("github.com") && read_file("entries.csv"))
  .then([] {
    // ^^^^^^ The original signature was <std::string, Buffer>,
    // however, the callback is only invoked with the amount of
    // arguments it's accepting.
  });

This makes it possible to attach a callback accepting nothing to every continuable_base.

Assigning a specific executor to then

Dispatching a callback through a specific executor is a common usage scenario and supported through the second argument of then:

auto executor = [](auto&& work) {
  // Dispatch the work here, store it for later
  // invocation or move it to another thread.
  std::forward<decltype(work)>(work)();
};

read_file("entries.csv")
  .then([](Buffer buffer) {
    // ...
  }, executor);
//   ^^^^^^^^

The supplied work callable may be stored and moved for later usage on a possible different thread or execution context.

Using fail and exceptions

Asynchronous exceptions are supported too. Exceptions that were set through promise_base::set_exception are forwarded to the first available registered handler that was attached through continuable_base::fail :

http_request("github.com")
  .then([] (std::string result) {
    // Is never called if an error occurs
  })
  .fail([] (std::exception_ptr ptr) {
    try {
      std::rethrow_exception(ptr);
    } catch(std::exception const& e) {
      // Handle the exception or error code here
    }
  });

Multiple handlers are allowed to be registered, however the asynchronous call hierarchy is aborted after the first called fail handler and only the closest handler below is called.

Continuable also supports error codes automatically if exceptions are disabled. Additionally it is possible to specify a custom error type through defining.

http_request("github.com")
  .then([] (std::string result) {
    // Is never called if an error occurs
  })
  .fail([] (std::error_condition error) {
    error.value();
    error.category();
  });

The error_type will be std::exception_ptr except if any of the following definitions is defined:

  • CONTINUABLE_WITH_NO_EXCEPTIONS: Define this to use std::error_condition as error_type and to disable exception support. When exceptions are disabled this definition is set automatically.
  • CONTINUABLE_WITH_CUSTOM_ERROR_TYPE: Define this to use a user defined error type.

Using next to handle all paths

Sometimes it's required to provide a continuation and error handler from the same object. In order to avoid overloading conflicts there is the special method continuable_base::next provided. The exception path overload is marked through the dispatch_error_tag :

struct handle_all_paths {
  void operator() (std::string result) {
    // ...
  }
  void operator() (cti::dispatch_error_tag, cti::error_type) {
    // ...
  }
};

// ...

http_request("github.com")
  .next(handle_all_paths{});