Promise.h 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /*
  2. * Copyright (c) 2021, 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(GlobalObject&, 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 Promise* create(GlobalObject&);
  24. explicit Promise(Object& prototype);
  25. virtual ~Promise() = default;
  26. State state() const { return m_state; }
  27. Value result() const { return m_result; }
  28. struct ResolvingFunctions {
  29. FunctionObject& resolve;
  30. FunctionObject& reject;
  31. };
  32. ResolvingFunctions create_resolving_functions();
  33. Value fulfill(Value value);
  34. Value reject(Value reason);
  35. Value perform_then(Value on_fulfilled, Value on_rejected, Optional<PromiseCapability> result_capability);
  36. protected:
  37. virtual void visit_edges(Visitor&) override;
  38. private:
  39. bool is_settled() const { return m_state == State::Fulfilled || m_state == State::Rejected; }
  40. void trigger_reactions() const;
  41. // 27.2.6 Properties of Promise Instances, https://tc39.es/ecma262/#sec-properties-of-promise-instances
  42. State m_state { State::Pending }; // [[PromiseState]]
  43. Value m_result; // [[PromiseResult]]
  44. Vector<PromiseReaction*> m_fulfill_reactions; // [[PromiseFulfillReactions]]
  45. Vector<PromiseReaction*> m_reject_reactions; // [[PromiseRejectReactions]]
  46. bool m_is_handled { false }; // [[PromiseIsHandled]]
  47. };
  48. }