promise_util.h 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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 "content/public/browser/browser_thread.h"
  8. #include "native_mate/converter.h"
  9. namespace atom {
  10. namespace util {
  11. class Promise : public base::RefCounted<Promise> {
  12. public:
  13. explicit Promise(v8::Isolate* isolate);
  14. v8::Isolate* isolate() const { return isolate_; }
  15. virtual v8::Local<v8::Promise> GetHandle() const;
  16. v8::Maybe<bool> Resolve() {
  17. return GetInner()->Resolve(isolate()->GetCurrentContext(),
  18. v8::Undefined(isolate()));
  19. }
  20. v8::Maybe<bool> Reject() {
  21. return GetInner()->Reject(isolate()->GetCurrentContext(),
  22. v8::Undefined(isolate()));
  23. }
  24. // Promise resolution is a microtask
  25. // We use the MicrotasksRunner to trigger the running of pending microtasks
  26. template <typename T>
  27. v8::Maybe<bool> Resolve(const T& value) {
  28. return GetInner()->Resolve(isolate()->GetCurrentContext(),
  29. mate::ConvertToV8(isolate(), value));
  30. }
  31. template <typename T>
  32. v8::Maybe<bool> Reject(const T& value) {
  33. return GetInner()->Reject(isolate()->GetCurrentContext(),
  34. mate::ConvertToV8(isolate(), value));
  35. }
  36. v8::Maybe<bool> RejectWithErrorMessage(const std::string& error);
  37. protected:
  38. virtual ~Promise();
  39. friend class base::RefCounted<Promise>;
  40. v8::Isolate* isolate_;
  41. private:
  42. v8::Local<v8::Promise::Resolver> GetInner() const {
  43. return resolver_.Get(isolate());
  44. }
  45. v8::Global<v8::Promise::Resolver> resolver_;
  46. DISALLOW_COPY_AND_ASSIGN(Promise);
  47. };
  48. } // namespace util
  49. } // namespace atom
  50. namespace mate {
  51. template <>
  52. struct Converter<atom::util::Promise*> {
  53. static v8::Local<v8::Value> ToV8(v8::Isolate* isolate,
  54. atom::util::Promise* val);
  55. // TODO(MarshallOfSound): Implement FromV8 to allow promise chaining
  56. // in native land
  57. // static bool FromV8(v8::Isolate* isolate,
  58. // v8::Local<v8::Value> val,
  59. // Promise* out);
  60. };
  61. } // namespace mate
  62. #endif // ATOM_COMMON_PROMISE_UTIL_H_