mirror of
https://github.com/LadybirdBrowser/ladybird.git
synced 2024-11-25 09:00:22 +00:00
LibCore: Check if a promise is already resolved in Promise::map()
This commit is contained in:
parent
50d8ef94ba
commit
51fefb57fc
Notes:
sideshowbarker
2024-07-16 23:59:28 +09:00
Author: https://github.com/krkk Commit: https://github.com/SerenityOS/serenity/commit/51fefb57fc Pull-request: https://github.com/SerenityOS/serenity/pull/20833 Reviewed-by: https://github.com/ADKaster ✅
2 changed files with 42 additions and 2 deletions
|
@ -61,6 +61,40 @@ TEST_CASE(promise_chain_handlers)
|
|||
EXPECT(!rejected);
|
||||
}
|
||||
|
||||
TEST_CASE(promise_map)
|
||||
{
|
||||
Core::EventLoop loop;
|
||||
|
||||
auto promise = MUST(Core::Promise<int>::try_create());
|
||||
auto mapped_promise = promise->map<int>([](int result) {
|
||||
return result * 2;
|
||||
});
|
||||
|
||||
loop.deferred_invoke([=] {
|
||||
promise->resolve(21);
|
||||
});
|
||||
|
||||
auto result = mapped_promise->await();
|
||||
EXPECT(!result.is_error());
|
||||
EXPECT_EQ(result.value(), 42);
|
||||
}
|
||||
|
||||
TEST_CASE(promise_map_already_resolved)
|
||||
{
|
||||
Core::EventLoop loop;
|
||||
|
||||
auto promise = MUST(Core::Promise<int>::try_create());
|
||||
promise->resolve(21);
|
||||
|
||||
auto mapped_promise = promise->map<int>([](int result) {
|
||||
return result * 2;
|
||||
});
|
||||
|
||||
auto result = mapped_promise->await();
|
||||
EXPECT(!result.is_error());
|
||||
EXPECT_EQ(result.value(), 42);
|
||||
}
|
||||
|
||||
TEST_CASE(threaded_promise_instantly_resolved)
|
||||
{
|
||||
Core::EventLoop loop;
|
||||
|
|
|
@ -60,9 +60,15 @@ public:
|
|||
|
||||
// Converts a Promise<A> to a Promise<B> using a function func: A -> B
|
||||
template<typename T>
|
||||
RefPtr<Promise<T>> map(Function<T(Result&)> func)
|
||||
NonnullRefPtr<Promise<T>> map(Function<T(Result&)> func)
|
||||
{
|
||||
RefPtr<Promise<T>> new_promise = Promise<T>::construct();
|
||||
NonnullRefPtr<Promise<T>> new_promise = Promise<T>::construct();
|
||||
|
||||
if (is_resolved())
|
||||
new_promise->resolve(func(m_result_or_rejection->value()));
|
||||
if (is_rejected())
|
||||
new_promise->reject(m_result_or_rejection->release_error());
|
||||
|
||||
on_resolution = [new_promise, func = move(func)](Result& result) -> ErrorOr<void> {
|
||||
new_promise->resolve(func(result));
|
||||
return {};
|
||||
|
|
Loading…
Reference in a new issue