Promise.h 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. public:
  14. enum class State {
  15. Pending,
  16. Fulfilled,
  17. Rejected,
  18. };
  19. enum class RejectionOperation {
  20. Reject,
  21. Handle,
  22. };
  23. static NonnullGCPtr<Promise> create(Realm&);
  24. virtual ~Promise() = default;
  25. State state() const { return m_state; }
  26. Value result() const { return m_result; }
  27. struct ResolvingFunctions {
  28. NonnullGCPtr<FunctionObject> resolve;
  29. NonnullGCPtr<FunctionObject> reject;
  30. };
  31. ResolvingFunctions create_resolving_functions();
  32. void fulfill(Value value);
  33. void reject(Value reason);
  34. Value perform_then(Value on_fulfilled, Value on_rejected, GCPtr<PromiseCapability> result_capability);
  35. bool is_handled() const { return m_is_handled; }
  36. void set_is_handled() { m_is_handled = true; }
  37. protected:
  38. explicit Promise(Object& prototype);
  39. virtual void visit_edges(Visitor&) override;
  40. private:
  41. bool is_settled() const { return m_state == State::Fulfilled || m_state == State::Rejected; }
  42. void trigger_reactions() const;
  43. // 27.2.6 Properties of Promise Instances, https://tc39.es/ecma262/#sec-properties-of-promise-instances
  44. State m_state { State::Pending }; // [[PromiseState]]
  45. Value m_result; // [[PromiseResult]]
  46. Vector<GCPtr<PromiseReaction>> m_fulfill_reactions; // [[PromiseFulfillReactions]]
  47. Vector<GCPtr<PromiseReaction>> m_reject_reactions; // [[PromiseRejectReactions]]
  48. bool m_is_handled { false }; // [[PromiseIsHandled]]
  49. };
  50. }