promise_util.h 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. // Copyright (c) 2018 GitHub, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #ifndef ATOM_COMMON_PROMISE_UTIL_H_
  5. #define ATOM_COMMON_PROMISE_UTIL_H_
  6. #include <string>
  7. #include <utility>
  8. #include "atom/common/api/locker.h"
  9. #include "atom/common/native_mate_converters/callback.h"
  10. #include "base/task/post_task.h"
  11. #include "content/public/browser/browser_task_traits.h"
  12. #include "content/public/browser/browser_thread.h"
  13. #include "native_mate/converter.h"
  14. namespace atom {
  15. namespace util {
  16. // A wrapper around the v8::Promise.
  17. //
  18. // This is a move-only type that should always be `std::move`d when passed to
  19. // callbacks, and it should be destroyed on the same thread of creation.
  20. class Promise {
  21. public:
  22. // Create a new promise.
  23. explicit Promise(v8::Isolate* isolate);
  24. // Wrap an existing v8 promise.
  25. Promise(v8::Isolate* isolate, v8::Local<v8::Promise::Resolver> handle);
  26. ~Promise();
  27. // Support moving.
  28. Promise(Promise&&);
  29. Promise& operator=(Promise&&);
  30. v8::Isolate* isolate() const { return isolate_; }
  31. v8::Local<v8::Context> GetContext() {
  32. return v8::Local<v8::Context>::New(isolate_, context_);
  33. }
  34. // helpers for promise resolution and rejection
  35. template <typename T>
  36. static void ResolvePromise(Promise promise, T result) {
  37. if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
  38. base::PostTaskWithTraits(
  39. FROM_HERE, {content::BrowserThread::UI},
  40. base::BindOnce(
  41. [](Promise promise, T result) { promise.Resolve(result); },
  42. std::move(promise), std::move(result)));
  43. } else {
  44. promise.Resolve(result);
  45. }
  46. }
  47. static void ResolveEmptyPromise(Promise promise) {
  48. if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
  49. base::PostTaskWithTraits(
  50. FROM_HERE, {content::BrowserThread::UI},
  51. base::BindOnce([](Promise promise) { promise.Resolve(); },
  52. std::move(promise)));
  53. } else {
  54. promise.Resolve();
  55. }
  56. }
  57. static void RejectPromise(Promise promise, std::string errmsg) {
  58. if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
  59. base::PostTaskWithTraits(FROM_HERE, {content::BrowserThread::UI},
  60. base::BindOnce(
  61. [](Promise promise, std::string errmsg) {
  62. promise.RejectWithErrorMessage(errmsg);
  63. },
  64. std::move(promise), std::move(errmsg)));
  65. } else {
  66. promise.RejectWithErrorMessage(errmsg);
  67. }
  68. }
  69. v8::Local<v8::Promise> GetHandle() const;
  70. v8::Maybe<bool> Resolve() {
  71. v8::HandleScope handle_scope(isolate());
  72. v8::MicrotasksScope script_scope(isolate(),
  73. v8::MicrotasksScope::kRunMicrotasks);
  74. v8::Context::Scope context_scope(
  75. v8::Local<v8::Context>::New(isolate(), GetContext()));
  76. return GetInner()->Resolve(GetContext(), v8::Undefined(isolate()));
  77. }
  78. v8::Maybe<bool> Reject() {
  79. v8::HandleScope handle_scope(isolate());
  80. v8::MicrotasksScope script_scope(isolate(),
  81. v8::MicrotasksScope::kRunMicrotasks);
  82. v8::Context::Scope context_scope(
  83. v8::Local<v8::Context>::New(isolate(), GetContext()));
  84. return GetInner()->Reject(GetContext(), v8::Undefined(isolate()));
  85. }
  86. // Please note that using Then is effectively the same as calling .then
  87. // in javascript. This means (a) it is not type safe and (b) please note
  88. // it is NOT type safe.
  89. // If the base::Callback you provide here is of type void(boolean) and you
  90. // resolve the promise with a string, Electron will compile successfully and
  91. // then that promise will be rejected as soon as you try to use it as the
  92. // mate converters doing work behind the scenes will throw an error for you.
  93. // This can be really hard to trace so until either
  94. // * This helper becomes typesafe (by templating the class instead of each
  95. // method)
  96. // * or the world goes mad
  97. // Please try your hardest not to use this method
  98. // The world thanks you
  99. template <typename... ResolveType>
  100. v8::MaybeLocal<v8::Promise> Then(base::Callback<void(ResolveType...)> cb) {
  101. static_assert(sizeof...(ResolveType) <= 1,
  102. "A promise's 'Then' callback should only receive at most one "
  103. "parameter");
  104. v8::HandleScope handle_scope(isolate());
  105. v8::Context::Scope context_scope(
  106. v8::Local<v8::Context>::New(isolate(), GetContext()));
  107. v8::Local<v8::Value> value = mate::ConvertToV8(isolate(), cb);
  108. v8::Local<v8::Function> handler = v8::Local<v8::Function>::Cast(value);
  109. return GetHandle()->Then(GetContext(), handler);
  110. }
  111. // Promise resolution is a microtask
  112. // We use the MicrotasksRunner to trigger the running of pending microtasks
  113. template <typename T>
  114. v8::Maybe<bool> Resolve(const T& value) {
  115. v8::HandleScope handle_scope(isolate());
  116. v8::MicrotasksScope script_scope(isolate(),
  117. v8::MicrotasksScope::kRunMicrotasks);
  118. v8::Context::Scope context_scope(
  119. v8::Local<v8::Context>::New(isolate(), GetContext()));
  120. return GetInner()->Resolve(GetContext(),
  121. mate::ConvertToV8(isolate(), value));
  122. }
  123. template <typename T>
  124. v8::Maybe<bool> Reject(const T& value) {
  125. v8::HandleScope handle_scope(isolate());
  126. v8::MicrotasksScope script_scope(isolate(),
  127. v8::MicrotasksScope::kRunMicrotasks);
  128. v8::Context::Scope context_scope(
  129. v8::Local<v8::Context>::New(isolate(), GetContext()));
  130. return GetInner()->Reject(GetContext(),
  131. mate::ConvertToV8(isolate(), value));
  132. }
  133. v8::Maybe<bool> RejectWithErrorMessage(const std::string& error);
  134. private:
  135. friend class CopyablePromise;
  136. v8::Local<v8::Promise::Resolver> GetInner() const {
  137. return resolver_.Get(isolate());
  138. }
  139. v8::Isolate* isolate_;
  140. v8::Global<v8::Context> context_;
  141. v8::Global<v8::Promise::Resolver> resolver_;
  142. DISALLOW_COPY_AND_ASSIGN(Promise);
  143. };
  144. // A wrapper of Promise that can be copied.
  145. //
  146. // This class should only be used when we have to pass Promise to a Chromium API
  147. // that does not take OnceCallback.
  148. class CopyablePromise {
  149. public:
  150. explicit CopyablePromise(const Promise& promise);
  151. CopyablePromise(const CopyablePromise&);
  152. ~CopyablePromise();
  153. template <typename T>
  154. static void ResolveCopyablePromise(const CopyablePromise& promise, T result) {
  155. if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
  156. base::PostTaskWithTraits(
  157. FROM_HERE, {content::BrowserThread::UI},
  158. base::BindOnce(Promise::ResolvePromise<T>, promise.GetPromise(),
  159. std::move(result)));
  160. } else {
  161. promise.GetPromise().Resolve(result);
  162. }
  163. }
  164. static void ResolveEmptyCopyablePromise(const CopyablePromise& promise) {
  165. if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
  166. base::PostTaskWithTraits(
  167. FROM_HERE, {content::BrowserThread::UI},
  168. base::BindOnce(Promise::ResolveEmptyPromise, promise.GetPromise()));
  169. } else {
  170. promise.GetPromise().Resolve();
  171. }
  172. }
  173. static void RejectCopyablePromise(const CopyablePromise& promise,
  174. std::string errmsg) {
  175. if (!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI)) {
  176. base::PostTaskWithTraits(
  177. FROM_HERE, {content::BrowserThread::UI},
  178. base::BindOnce(Promise::RejectPromise, promise.GetPromise(),
  179. std::move(errmsg)));
  180. } else {
  181. promise.GetPromise().RejectWithErrorMessage(errmsg);
  182. }
  183. }
  184. Promise GetPromise() const;
  185. private:
  186. using CopyablePersistent =
  187. v8::CopyablePersistentTraits<v8::Promise::Resolver>::CopyablePersistent;
  188. v8::Isolate* isolate_;
  189. CopyablePersistent handle_;
  190. };
  191. } // namespace util
  192. } // namespace atom
  193. namespace mate {
  194. template <>
  195. struct Converter<atom::util::Promise> {
  196. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  197. const atom::util::Promise& val);
  198. // TODO(MarshallOfSound): Implement FromV8 to allow promise chaining
  199. // in native land
  200. // static bool FromV8(v8::Isolate* isolate,
  201. // v8::Local<v8::Value> val,
  202. // Promise* out);
  203. };
  204. } // namespace mate
  205. #endif // ATOM_COMMON_PROMISE_UTIL_H_