/* * Copyright (c) 2021, Kyle Pereira * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include #include namespace Core { template class Promise : public Object { C_OBJECT(Promise); public: Function on_resolved; void resolve(Result&& result) { m_pending = move(result); if (on_resolved) on_resolved(m_pending.value()); } bool is_resolved() { return m_pending.has_value(); }; Result await() { while (!is_resolved()) { Core::EventLoop::current().pump(); } return m_pending.release_value(); } // Converts a Promise to a Promise using a function func: A -> B template RefPtr> map(T func(Result&)) { RefPtr> new_promise = Promise::construct(); on_resolved = [new_promise, func](Result& result) { auto t = func(result); new_promise->resolve(move(t)); }; return new_promise; } private: Promise() = default; Optional m_pending; }; }