get_or_default promise function

This commit is contained in:
2018-12-14 19:11:42 +07:00
parent 3bc274228c
commit 75177fb5f8
2 changed files with 50 additions and 0 deletions

View File

@@ -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();
}

View File

@@ -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<int>(std::logic_error("hello fail"));
REQUIRE(p.get_or_default(84) == 84);
}
{
auto p = pr::promise<int>();
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<int>();
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<void>(std::logic_error("hello fail"));
REQUIRE_NOTHROW(p.get_or_default());
}
}
}
TEST_CASE("promise_transformations") {