LibCore: Slightly rework the Core::Promise API

The previous iteration of this API was somewhat odd and rough in random
places, which degraded usability and made less than perfect sense.
This commit reworks the API to be a little closer to more
conventional promise APIs (a la javascript promises).

Also adds a test to ensure the class even works.
This commit is contained in:
Ali Mohammad Pur 2023-07-08 01:30:27 +03:30 committed by Linus Groh
commit 0c5c75e8a4
Notes: sideshowbarker 2024-07-17 10:05:47 +09:00
9 changed files with 150 additions and 38 deletions

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 2023, Ali Mohammad Pur <mpfard@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <LibCore/EventLoop.h>
#include <LibCore/Promise.h>
#include <LibTest/TestSuite.h>
TEST_CASE(promise_await_async_event)
{
Core::EventLoop loop;
auto promise = MUST(Core::Promise<int>::try_create());
loop.deferred_invoke([=] {
promise->resolve(42);
});
auto& result = promise->await();
EXPECT(!result.is_error());
EXPECT_EQ(result.value(), 42);
}
TEST_CASE(promise_await_async_event_rejection)
{
Core::EventLoop loop;
auto promise = MUST(Core::Promise<int>::try_create());
loop.deferred_invoke([=] {
promise->reject(AK::Error::from_string_literal("lol no"));
});
auto& result = promise->await();
EXPECT(result.is_error());
EXPECT_EQ(result.error().string_literal(), "lol no"sv);
}
TEST_CASE(promise_chain_handlers)
{
Core::EventLoop loop;
bool resolved = false;
bool rejected = false;
NonnullRefPtr<Core::Promise<int>> promise = MUST(Core::Promise<int>::try_create())
->when_resolved([&](int&) -> ErrorOr<void> { resolved = true; return {}; })
.when_rejected([&](AK::Error const&) { rejected = true; });
loop.deferred_invoke([=] {
promise->resolve(42);
});
promise->await();
EXPECT(resolved);
EXPECT(!rejected);
}