diff --git a/promise.hpp b/promise.hpp index 85931a8..84524d3 100644 --- a/promise.hpp +++ b/promise.hpp @@ -297,6 +297,14 @@ namespace promise_hpp return state_->get(); } + const T& get_or_default(const T& def) const noexcept { + try { + return get(); + } catch (...) { + return def; + } + } + void wait() const noexcept { state_->wait(); } @@ -680,6 +688,14 @@ namespace promise_hpp state_->get(); } + void get_or_default() const noexcept { + try { + return get(); + } catch (...) { + // nothing + } + } + void wait() const noexcept { state_->wait(); } diff --git a/promise_tests.cpp b/promise_tests.cpp index 80aa228..6da18da 100644 --- a/promise_tests.cpp +++ b/promise_tests.cpp @@ -998,6 +998,40 @@ TEST_CASE("get_and_wait") { REQUIRE(p.get() == 42); } } + SECTION("get_or_default") { + { + auto p = pr::make_resolved_promise(42); + REQUIRE(p.get_or_default(84) == 42); + } + { + auto p = pr::make_rejected_promise(std::logic_error("hello fail")); + REQUIRE(p.get_or_default(84) == 84); + } + { + auto p = pr::promise(); + auto_thread t{[p]() mutable { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + p.resolve(42); + }}; + REQUIRE(p.get_or_default(84) == 42); + } + { + auto p = pr::promise(); + auto_thread t{[p]() mutable { + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + p.reject(std::logic_error("hello fail")); + }}; + REQUIRE(p.get_or_default(84) == 84); + } + { + auto p = pr::make_resolved_promise(); + REQUIRE_NOTHROW(p.get_or_default()); + } + { + auto p = pr::make_rejected_promise(std::logic_error("hello fail")); + REQUIRE_NOTHROW(p.get_or_default()); + } + } } TEST_CASE("promise_transformations") {