Promise.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Vector.h>
  8. #include <LibJS/Runtime/Object.h>
  9. namespace JS {
  10. ThrowCompletionOr<Object*> promise_resolve(VM&, Object& constructor, Value);
  11. class Promise : public Object {
  12. JS_OBJECT(Promise, Object);
  13. JS_DECLARE_ALLOCATOR(Promise);
  14. public:
  15. enum class State {
  16. Pending,
  17. Fulfilled,
  18. Rejected,
  19. };
  20. enum class RejectionOperation {
  21. Reject,
  22. Handle,
  23. };
  24. static NonnullGCPtr<Promise> create(Realm&);
  25. virtual ~Promise() = default;
  26. State state() const { return m_state; }
  27. Value result() const { return m_result; }
  28. struct ResolvingFunctions {
  29. NonnullGCPtr<FunctionObject> resolve;
  30. NonnullGCPtr<FunctionObject> reject;
  31. };
  32. ResolvingFunctions create_resolving_functions();
  33. void fulfill(Value value);
  34. void reject(Value reason);
  35. Value perform_then(Value on_fulfilled, Value on_rejected, GCPtr<PromiseCapability> result_capability);
  36. bool is_handled() const { return m_is_handled; }
  37. void set_is_handled() { m_is_handled = true; }
  38. protected:
  39. explicit Promise(Object& prototype);
  40. virtual void visit_edges(Visitor&) override;
  41. private:
  42. bool is_settled() const { return m_state == State::Fulfilled || m_state == State::Rejected; }
  43. void trigger_reactions() const;
  44. // 27.2.6 Properties of Promise Instances, https://tc39.es/ecma262/#sec-properties-of-promise-instances
  45. State m_state { State::Pending }; // [[PromiseState]]
  46. Value m_result; // [[PromiseResult]]
  47. Vector<GCPtr<PromiseReaction>> m_fulfill_reactions; // [[PromiseFulfillReactions]]
  48. Vector<GCPtr<PromiseReaction>> m_reject_reactions; // [[PromiseRejectReactions]]
  49. bool m_is_handled { false }; // [[PromiseIsHandled]]
  50. };
  51. }