Promise.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /*
  2. * Copyright (c) 2021, Kyle Pereira <hey@xylepereira.me>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibCore/EventLoop.h>
  8. #include <LibCore/Object.h>
  9. namespace Core {
  10. template<typename Result>
  11. class Promise : public Object {
  12. C_OBJECT(Promise);
  13. public:
  14. Function<void(Result&)> on_resolved;
  15. void resolve(Result&& result)
  16. {
  17. m_pending = move(result);
  18. if (on_resolved)
  19. on_resolved(m_pending.value());
  20. }
  21. bool is_resolved()
  22. {
  23. return m_pending.has_value();
  24. };
  25. Result await()
  26. {
  27. while (!is_resolved()) {
  28. Core::EventLoop::current().pump();
  29. }
  30. return m_pending.release_value();
  31. }
  32. // Converts a Promise<A> to a Promise<B> using a function func: A -> B
  33. template<typename T>
  34. RefPtr<Promise<T>> map(T func(Result&))
  35. {
  36. RefPtr<Promise<T>> new_promise = Promise<T>::construct();
  37. on_resolved = [new_promise, func](Result& result) mutable {
  38. auto t = func(result);
  39. new_promise->resolve(move(t));
  40. };
  41. return new_promise;
  42. }
  43. private:
  44. Promise() = default;
  45. Optional<Result> m_pending;
  46. };
  47. }