Skip to content

Commit

Permalink
feat: Add Promise.resolve utility method.
Browse files Browse the repository at this point in the history
  • Loading branch information
dylanahsmith committed Feb 9, 2016
1 parent 1632d38 commit 0cdf17a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
5 changes: 5 additions & 0 deletions lib/promise.rb
Expand Up @@ -12,6 +12,11 @@ class Promise

attr_reader :state, :value, :reason, :backtrace

def self.resolve(obj)
return obj if obj.instance_of?(self)
new.tap { |promise| promise.fulfill(obj) }
end

def initialize
@state = :pending
@callbacks = []
Expand Down
17 changes: 17 additions & 0 deletions spec/unit/promise_spec.rb
Expand Up @@ -408,5 +408,22 @@
expect(subject.sync).to be(value)
end
end

describe '.resolve' do
it 'returns a fulfilled promise from a non-promise' do
promise = Promise.resolve(123)
expect(promise.fulfilled?).to eq(true)
expect(promise.value).to eq(123)
end

it 'assumes the state of a given promise' do
promise = Promise.new
new_promise = Promise.resolve(promise)
expect(new_promise.pending?).to eq(true)
promise.fulfill(42)
expect(new_promise.fulfilled?).to eq(true)
expect(new_promise.value).to eq(42)
end
end
end
end

0 comments on commit 0cdf17a

Please sign in to comment.