mirror of
https://github.com/RGBCube/serenity
synced 2025-07-25 21:57:43 +00:00
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:
parent
5a0ad6812c
commit
0c5c75e8a4
9 changed files with 150 additions and 38 deletions
59
Tests/LibCore/TestLibCorePromise.cpp
Normal file
59
Tests/LibCore/TestLibCorePromise.cpp
Normal 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);
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue