Promise.h 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  4. * You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #ifndef mozilla_dom_Promise_h
  6. #define mozilla_dom_Promise_h
  7. #include "mozilla/Attributes.h"
  8. #include "mozilla/ErrorResult.h"
  9. #include "mozilla/TimeStamp.h"
  10. #include "mozilla/TypeTraits.h"
  11. #include "mozilla/dom/BindingDeclarations.h"
  12. #include "nsCycleCollectionParticipant.h"
  13. #include "mozilla/dom/PromiseBinding.h"
  14. #include "mozilla/dom/ToJSValue.h"
  15. #include "mozilla/WeakPtr.h"
  16. #include "nsWrapperCache.h"
  17. #include "nsAutoPtr.h"
  18. #include "js/TypeDecls.h"
  19. #include "jspubtd.h"
  20. class nsIGlobalObject;
  21. namespace mozilla {
  22. namespace dom {
  23. class AnyCallback;
  24. class DOMError;
  25. class MediaStreamError;
  26. class PromiseInit;
  27. class PromiseNativeHandler;
  28. class PromiseDebugging;
  29. #define NS_PROMISE_IID \
  30. { 0x1b8d6215, 0x3e67, 0x43ba, \
  31. { 0x8a, 0xf9, 0x31, 0x5e, 0x8f, 0xce, 0x75, 0x65 } }
  32. class Promise : public nsISupports,
  33. public SupportsWeakPtr<Promise>
  34. {
  35. friend class PromiseTask;
  36. friend class PromiseWorkerProxy;
  37. friend class PromiseWorkerProxyRunnable;
  38. public:
  39. NS_DECLARE_STATIC_IID_ACCESSOR(NS_PROMISE_IID)
  40. NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  41. NS_DECL_CYCLE_COLLECTION_SCRIPT_HOLDER_CLASS(Promise)
  42. MOZ_DECLARE_WEAKREFERENCE_TYPENAME(Promise)
  43. // Promise creation tries to create a JS reflector for the Promise, so is
  44. // fallible. Furthermore, we don't want to do JS-wrapping on a 0-refcount
  45. // object, so we addref before doing that and return the addrefed pointer
  46. // here.
  47. static already_AddRefed<Promise>
  48. Create(nsIGlobalObject* aGlobal, ErrorResult& aRv);
  49. // Reports a rejected Promise by sending an error report.
  50. static void ReportRejectedPromise(JSContext* aCx, JS::HandleObject aPromise);
  51. typedef void (Promise::*MaybeFunc)(JSContext* aCx,
  52. JS::Handle<JS::Value> aValue);
  53. void MaybeResolve(JSContext* aCx,
  54. JS::Handle<JS::Value> aValue);
  55. void MaybeReject(JSContext* aCx,
  56. JS::Handle<JS::Value> aValue);
  57. // Helpers for using Promise from C++.
  58. // Most DOM objects are handled already. To add a new type T, add a
  59. // ToJSValue overload in ToJSValue.h.
  60. // aArg is a const reference so we can pass rvalues like integer constants
  61. template <typename T>
  62. void MaybeResolve(const T& aArg) {
  63. MaybeSomething(aArg, &Promise::MaybeResolve);
  64. }
  65. void MaybeResolveWithUndefined();
  66. inline void MaybeReject(nsresult aArg) {
  67. MOZ_ASSERT(NS_FAILED(aArg));
  68. MaybeSomething(aArg, &Promise::MaybeReject);
  69. }
  70. inline void MaybeReject(ErrorResult& aArg) {
  71. MOZ_ASSERT(aArg.Failed());
  72. MaybeSomething(aArg, &Promise::MaybeReject);
  73. }
  74. void MaybeReject(const RefPtr<MediaStreamError>& aArg);
  75. void MaybeRejectWithUndefined();
  76. // DO NOT USE MaybeRejectBrokenly with in new code. Promises should be
  77. // rejected with Error instances.
  78. // Note: MaybeRejectBrokenly is a template so we can use it with DOMError
  79. // without instantiating the DOMError specialization of MaybeSomething in
  80. // every translation unit that includes this header, because that would
  81. // require use to include DOMError.h either here or in all those translation
  82. // units.
  83. template<typename T>
  84. void MaybeRejectBrokenly(const T& aArg); // Not implemented by default; see
  85. // specializations in the .cpp for
  86. // the T values we support.
  87. // Called by DOM to let us execute our callbacks. May be called recursively.
  88. // Returns true if at least one microtask was processed.
  89. static bool PerformMicroTaskCheckpoint();
  90. static void PerformWorkerMicroTaskCheckpoint();
  91. static void PerformWorkerDebuggerMicroTaskCheckpoint();
  92. // WebIDL
  93. nsIGlobalObject* GetParentObject() const
  94. {
  95. return mGlobal;
  96. }
  97. // Do the equivalent of Promise.resolve in the compartment of aGlobal. The
  98. // compartment of aCx is ignored. Errors are reported on the ErrorResult; if
  99. // aRv comes back !Failed(), this function MUST return a non-null value.
  100. static already_AddRefed<Promise>
  101. Resolve(nsIGlobalObject* aGlobal, JSContext* aCx,
  102. JS::Handle<JS::Value> aValue, ErrorResult& aRv);
  103. // Do the equivalent of Promise.reject in the compartment of aGlobal. The
  104. // compartment of aCx is ignored. Errors are reported on the ErrorResult; if
  105. // aRv comes back !Failed(), this function MUST return a non-null value.
  106. static already_AddRefed<Promise>
  107. Reject(nsIGlobalObject* aGlobal, JSContext* aCx,
  108. JS::Handle<JS::Value> aValue, ErrorResult& aRv);
  109. // Do the equivalent of Promise.all in the current compartment of aCx. Errors
  110. // are reported on the ErrorResult; if aRv comes back !Failed(), this function
  111. // MUST return a non-null value.
  112. static already_AddRefed<Promise>
  113. All(JSContext* aCx, const nsTArray<RefPtr<Promise>>& aPromiseList,
  114. ErrorResult& aRv);
  115. void
  116. Then(JSContext* aCx,
  117. // aCalleeGlobal may not be in the compartment of aCx, when called over
  118. // Xrays.
  119. JS::Handle<JSObject*> aCalleeGlobal,
  120. AnyCallback* aResolveCallback, AnyCallback* aRejectCallback,
  121. JS::MutableHandle<JS::Value> aRetval,
  122. ErrorResult& aRv);
  123. JSObject* PromiseObj() const
  124. {
  125. return mPromiseObj;
  126. }
  127. void AppendNativeHandler(PromiseNativeHandler* aRunnable);
  128. JSObject* GlobalJSObject() const;
  129. JSCompartment* Compartment() const;
  130. // Create a dom::Promise from a given SpiderMonkey Promise object.
  131. // aPromiseObj MUST be in the compartment of aGlobal's global JS object.
  132. static already_AddRefed<Promise>
  133. CreateFromExisting(nsIGlobalObject* aGlobal,
  134. JS::Handle<JSObject*> aPromiseObj);
  135. enum class PromiseState {
  136. Pending,
  137. Resolved,
  138. Rejected
  139. };
  140. PromiseState State() const;
  141. protected:
  142. struct PromiseCapability;
  143. // Do NOT call this unless you're Promise::Create or
  144. // Promise::CreateFromExisting. I wish we could enforce that from inside this
  145. // class too, somehow.
  146. explicit Promise(nsIGlobalObject* aGlobal);
  147. virtual ~Promise();
  148. // Do JS-wrapping after Promise creation. Passing null for aDesiredProto will
  149. // use the default prototype for the sort of Promise we have.
  150. void CreateWrapper(JS::Handle<JSObject*> aDesiredProto, ErrorResult& aRv);
  151. private:
  152. template <typename T>
  153. void MaybeSomething(T& aArgument, MaybeFunc aFunc) {
  154. MOZ_ASSERT(PromiseObj()); // It was preserved!
  155. AutoEntryScript aes(mGlobal, "Promise resolution or rejection");
  156. JSContext* cx = aes.cx();
  157. JS::Rooted<JS::Value> val(cx);
  158. if (!ToJSValue(cx, aArgument, &val)) {
  159. HandleException(cx);
  160. return;
  161. }
  162. (this->*aFunc)(cx, val);
  163. }
  164. void HandleException(JSContext* aCx);
  165. RefPtr<nsIGlobalObject> mGlobal;
  166. JS::Heap<JSObject*> mPromiseObj;
  167. };
  168. NS_DEFINE_STATIC_IID_ACCESSOR(Promise, NS_PROMISE_IID)
  169. } // namespace dom
  170. } // namespace mozilla
  171. #endif // mozilla_dom_Promise_h