Class: Dommy::PromiseValue

Inherits:
Object
  • Object
show all
Defined in:
lib/dommy/promise.rb

Overview

Note: ‘PromiseConstructor` and `PromiseSettler` live in `Dommy::Bridge::*` — they’re bridge-adapter classes for the ‘JS.global` view, not part of the public DOM surface.

Defined Under Namespace

Classes: Handler

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(window) ⇒ PromiseValue

Returns a new instance of PromiseValue.



47
48
49
50
51
52
# File 'lib/dommy/promise.rb', line 47

def initialize(window)
  @window = window
  @state = :pending
  @value = nil
  @handlers = []
end

Class Method Details

.reject(window, reason) ⇒ Object



41
42
43
44
45
# File 'lib/dommy/promise.rb', line 41

def self.reject(window, reason)
  promise = new(window)
  promise.reject(reason)
  promise
end

.resolve(window, value) ⇒ Object



35
36
37
38
39
# File 'lib/dommy/promise.rb', line 35

def self.resolve(window, value)
  promise = new(window)
  promise.fulfill(value)
  promise
end

Instance Method Details

#__js_call__(method, args) ⇒ Object



54
55
56
57
58
59
60
61
62
63
# File 'lib/dommy/promise.rb', line 54

def __js_call__(method, args)
  case method
  when "then"
    attach_then(args[0], args[1])
  when "catch"
    attach_then(nil, args[0])
  else
    nil
  end
end

#awaitObject

Synchronously unwrap the promise’s settled value, or raise its rejection. Dommy’s scheduler is deterministic, so “wait” is spelled “drain queued microtasks then read the state.”

This is the bridge between dommy’s async APIs (fetch, etc.) and Ruby tests that want to write straight-line code:

response = win.__js_call__("fetch", [url]).await
text     = response.text

Raises ‘RuntimeError` if the promise is still pending after a microtask drain — that’s a sign that real-time work (e.g. a ‘setTimeout`) needs to advance via `advance_time` first.



86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/dommy/promise.rb', line 86

def await
  @window&.scheduler&.drain_microtasks

  case @state
  when :fulfilled
    @value
  when :rejected
    raise unwrap_rejection(@value)
  else
    raise "Promise#await: still pending after microtask drain"
  end
end

#fulfill(value) ⇒ Object



65
66
67
# File 'lib/dommy/promise.rb', line 65

def fulfill(value)
  settle(:fulfilled, value)
end

#reject(reason) ⇒ Object



69
70
71
# File 'lib/dommy/promise.rb', line 69

def reject(reason)
  settle(:rejected, reason)
end