2021-07-15 14:13:02 +10:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2021, Kyle Pereira <hey@xylepereira.me>
|
|
|
|
*
|
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <LibCore/EventLoop.h>
|
|
|
|
#include <LibCore/Object.h>
|
|
|
|
|
|
|
|
namespace Core {
|
2022-12-29 14:53:05 +01:00
|
|
|
|
2021-07-15 14:13:02 +10:00
|
|
|
template<typename Result>
|
|
|
|
class Promise : public Object {
|
|
|
|
C_OBJECT(Promise);
|
|
|
|
|
|
|
|
public:
|
|
|
|
Function<void(Result&)> on_resolved;
|
|
|
|
|
|
|
|
void resolve(Result&& result)
|
|
|
|
{
|
2022-12-29 14:53:05 +01:00
|
|
|
m_pending_or_error = move(result);
|
|
|
|
|
2021-07-15 14:13:02 +10:00
|
|
|
if (on_resolved)
|
2022-12-29 14:53:05 +01:00
|
|
|
on_resolved(m_pending_or_error.value());
|
|
|
|
}
|
|
|
|
|
|
|
|
void cancel(Error error)
|
|
|
|
{
|
|
|
|
m_pending_or_error = move(error);
|
2021-07-15 14:13:02 +10:00
|
|
|
}
|
|
|
|
|
2022-12-29 14:53:05 +01:00
|
|
|
bool is_canceled()
|
2021-07-15 14:13:02 +10:00
|
|
|
{
|
2022-12-29 14:53:05 +01:00
|
|
|
return m_pending_or_error.has_value() && m_pending_or_error->is_error();
|
|
|
|
}
|
2021-07-15 14:13:02 +10:00
|
|
|
|
2022-12-29 14:53:05 +01:00
|
|
|
bool is_resolved() const
|
2021-07-15 14:13:02 +10:00
|
|
|
{
|
2022-12-29 14:53:05 +01:00
|
|
|
return m_pending_or_error.has_value() && !m_pending_or_error->is_error();
|
|
|
|
}
|
|
|
|
|
|
|
|
ErrorOr<Result> await()
|
|
|
|
{
|
|
|
|
while (!m_pending_or_error.has_value())
|
2021-07-15 14:13:02 +10:00
|
|
|
Core::EventLoop::current().pump();
|
2022-12-29 14:53:05 +01:00
|
|
|
|
|
|
|
return m_pending_or_error.release_value();
|
2021-07-15 14:13:02 +10:00
|
|
|
}
|
|
|
|
|
|
|
|
// Converts a Promise<A> to a Promise<B> using a function func: A -> B
|
|
|
|
template<typename T>
|
|
|
|
RefPtr<Promise<T>> map(T func(Result&))
|
|
|
|
{
|
|
|
|
RefPtr<Promise<T>> new_promise = Promise<T>::construct();
|
2022-11-19 01:09:53 +00:00
|
|
|
on_resolved = [new_promise, func](Result& result) {
|
2021-07-15 14:13:02 +10:00
|
|
|
auto t = func(result);
|
|
|
|
new_promise->resolve(move(t));
|
|
|
|
};
|
|
|
|
return new_promise;
|
|
|
|
}
|
2021-10-31 23:38:04 +01:00
|
|
|
|
|
|
|
private:
|
|
|
|
Promise() = default;
|
2022-12-29 14:50:05 +01:00
|
|
|
Promise(Object* parent)
|
|
|
|
: Object(parent)
|
|
|
|
{
|
|
|
|
}
|
2021-10-31 23:38:04 +01:00
|
|
|
|
2022-12-29 14:53:05 +01:00
|
|
|
Optional<ErrorOr<Result>> m_pending_or_error;
|
2021-07-15 14:13:02 +10:00
|
|
|
};
|
2022-12-29 14:53:05 +01:00
|
|
|
|
2021-07-15 14:13:02 +10:00
|
|
|
}
|