Skip to content

Allow root promise body to be set later #269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion lib/concurrent/promise.rb
Original file line number Diff line number Diff line change
Expand Up @@ -230,12 +230,22 @@ def self.reject(reason, opts = {})
Promise.new(opts).tap { |p| p.send(:synchronized_set_state!, false, nil, reason) }
end

# allow root promise body to be set later
# @example
# pr = Promise.new
# pr.with_body { :v }.execute.value # => :v
def with_body(&block)
raise 'supported only on root promises' unless root?
mutex.synchronize { @promise_body = block }
self
end

# @return [Promise]
def execute
if root?
if compare_and_set_state(:pending, :unscheduled)
set_pending
realize(@promise_body)
realize(mutex.synchronize { @promise_body })
end
else
@parent.execute
Expand Down
24 changes: 24 additions & 0 deletions spec/concurrent/promise_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -517,6 +517,30 @@ def get_ivar_from_args(opts)
expect(p2.value).to eq 22
expect(p3.value).to eq 67
end

it 'the body of root promise can be set later externally' do
p = Promise.new(executor: executor)
ch = p.then(&:to_s)
p.with_body { :value }.execute
p.execute

expect(p.value).to eq :value
expect(p.state).to eq :fulfilled

expect(ch.value).to eq 'value'
expect(ch.state).to eq :fulfilled

p = Promise.new(executor: executor)
ch = p.then(&:inspect)
p.execute

expect(p.value).to eq nil
expect(p.state).to eq :fulfilled

expect(ch.value).to eq 'nil'
expect(ch.state).to eq :fulfilled
end

end

context 'rejection' do
Expand Down