Promise.h 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. private:
  14. Optional<Result> m_pending;
  15. public:
  16. Function<void(Result&)> on_resolved;
  17. void resolve(Result&& result)
  18. {
  19. m_pending = move(result);
  20. if (on_resolved)
  21. on_resolved(m_pending.value());
  22. }
  23. bool is_resolved()
  24. {
  25. return m_pending.has_value();
  26. };
  27. Result await()
  28. {
  29. while (!is_resolved()) {
  30. Core::EventLoop::current().pump();
  31. }
  32. return m_pending.release_value();
  33. }
  34. // Converts a Promise<A> to a Promise<B> using a function func: A -> B
  35. template<typename T>
  36. RefPtr<Promise<T>> map(T func(Result&))
  37. {
  38. RefPtr<Promise<T>> new_promise = Promise<T>::construct();
  39. on_resolved = [new_promise, func](Result& result) mutable {
  40. auto t = func(result);
  41. new_promise->resolve(move(t));
  42. };
  43. return new_promise;
  44. }
  45. };
  46. }