Asynchronous Queries
This example shows how to use the libogmios library to asynchronously execute multiple queries. This is useful for applications that need to query the chain frequently:
// Third-party libraries #include <nlohmann/json.hpp> #include <ogmios/client.hpp> #include <spdlog/spdlog.h> using json = nlohmann::json; auto main() -> int { auto batch_size = 10; // Create a client to manage the Ogmios server connection. // The URL defaults to ws://localhost:1337 auto client = ogmios::Client(); // Setup the logging callback to print information to stdout. spdlog::set_level(spdlog::level::debug); // Set global log level client.setLoggerCallback( [](int level, const std::string &msg) { spdlog::log(static_cast<spdlog::level::level_enum>(level), msg); } ); // Make calls without waiting for a response. auto future_results = std::vector<std::future<json>>(); for (auto i = 0; i < batch_size; i++) future_results.push_back(client.queryBlockHeight()); // Accumulate all the results auto results = std::vector<json>(); for (auto &future : future_results) results.push_back(future.get()); for (auto &result : results) spdlog::info( "Block height: {} (ID: \"{}\")", result["result"].get<size_t>(), result["id"].get<std::string>() ); return 0; } // main
Example output: