Git Product home page Git Product logo

promise.rb's Introduction

promise.rb Build Status Code Climate Coverage Status

Ruby implementation of the Promises/A+ spec. 100% mutation coverage, tested on MRI 1.9, 2.0, 2.1, 2.2, Rubinius, and JRuby.

Similar projects:

Note that promise.rb is probably not thread safe.

Installation

Add this line to your application's Gemfile:

gem 'promise.rb'

And then execute:

$ bundle

Or install it yourself as:

$ gem install promise.rb

Usage

This guide assumes that you are familiar with the Promises/A+ spec. It's a quick read, though.

promise.rb comes with a very primitive way of scheduling callback dispatch. It immediately executes the callback, instead of scheduling it for execution after Promise#fulfill or Promise#reject, as demanded by the spec:

onFulfilled or onRejected must not be called until the execution context stack contains only platform code.

Compliance can be achieved, for example, by running an event reactor like EventMachine:

require 'promise'
require 'eventmachine'

class MyPromise < Promise
  def defer
    EM.next_tick { yield }
  end
end

Now you can create MyPromise objects, and fulfill (or reject) them, as well as add callbacks to them:

def nonblocking_stuff
  promise = MyPromise.new
  EM.next_tick { promise.fulfill('value') }
  promise
end

EM.run do
  nonblocking_stuff.then { |value| p value }
  nonblocking_stuff.then(proc { |value| p value })
end

Rejection works similarly:

def failing_stuff
  promise = MyPromise.new
  EM.next_tick { promise.reject('reason') }
  promise
end

EM.run do
  failing_stuff.then(proc { |value| }, proc { |reason| p reason })
end

Waiting for fulfillment/rejection

promise.rb also comes with the utility method Promise#sync, which waits for the promise to be fulfilled and returns the value, or for it to be rejected and re-raises the reason. Using #sync requires you to implement #wait. You could for example cooperatively schedule fibers waiting for different promises:

require 'fiber'
require 'promise'
require 'eventmachine'

class MyPromise < Promise
  def defer
    EM.next_tick { yield }
  end

  def wait
    fiber = Fiber.current
    resume = proc do |arg|
      defer { fiber.resume(arg) }
    end

    self.then(resume, resume)
    Fiber.yield
  end
end

EM.run do
  promise = MyPromise.new
  Fiber.new { p promise.sync }.resume
  promise.fulfill
end

Or have the rejection reason re-raised from #sync:

EM.run do
  promise = MyPromise.new

  Fiber.new do
    begin
      promise.sync
    rescue
      p $!
    end
  end.resume

  promise.reject('reason')
end

Chaining promises

As per the A+ spec, every call to #then returns a new promise, which assumes the first promise's state. That means it passes its #fulfill and #reject methods to first promise's #then, short-circuiting the two promises. In case a callback returns a promise, it'll instead assume that promise's state.

Imagine the #fulfill and #reject calls in the following example happening somewhere in a background Fiber or so.

require 'promise'

Promise.new
  .tap(&:fulfill)
  .then { Promise.new.tap(&:fulfill) }
  .then { Promise.new.tap(&:reject) }
  .then(nil, proc { |reason| p reason })

In order to use the result of multiple promises, they can be grouped using Promise.all for chaining.

sum_promise = Promise.all([promise1, promise2]).then do |value1, value2|
  value1 + value2
end

Progress callbacks

Very simple progress callbacks, as per Promises/A, are supported as well. They have been dropped in A+, but I found them to be a useful mechanism - if kept simple. Callback dispatch happens immediately in the call to #progress, in the order of definition via #on_progress. Also note that #on_progress does not return a new promise for chaining - the progress mechanism is meant to be very lightweight, and ignores many of the constraints and guarantees of then.

promise = MyPromise.new
promise.on_progress { |status| p status }
promise.progress(:anything)

Unlicense

promise.rb is free and unencumbered public domain software. For more information, see unlicense.org or the accompanying UNLICENSE file.

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

promise.rb's People

Contributors

amomchilov avatar arthurschreiber avatar dylanahsmith avatar rixlabs avatar sheerun avatar teoljungberg avatar wmertens avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

promise.rb's Issues

Event machine example breaks when an error is raised from an handler

When an handler raises an error, it will reject the next promise, but also let the error bubble up the call stack.

When using the example EM Promise subclass in an RSpec spec, this will generate weird behaviors:

  • if only 1 test exists, it will pass with the message 'Empty test suite.'
  • if other tests exist, we'll get the following trace in all tests:
RuntimeError: can't modify frozen object
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:274:in `extend_object'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:274:in `extend'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:274:in `finish'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/example.rb:139:in `run'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:390:in `block in run_examples'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:386:in `map'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:386:in `run_examples'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/example_group.rb:371:in `run'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:28:in `block (2 levels) in run'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:28:in `map'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:28:in `block in run'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/reporter.rb:34:in `report'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/command_line.rb:25:in `run'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:80:in `run'
/usr/local/var/rbenv/versions/1.9.3-p448/lib/ruby/gems/1.9.1/gems/rspec-core-2.13.1/lib/rspec/core/runner.rb:17:in `block in autorun'

This happens will all rspec versions I tested.

I suggest explaining that in the docs, I almost gave up on the library because I thought it was a bug in it.

Thank for it, btw, I like the API and being able to use any 'scheduler'.

Event Machine

Hi,

I opened an Issue but I just need some help relate to promise.rb.
I know and use Promises with q.js and I was trying a ruby equivalent.

I'm not an expert with EM but I tried the first examples and I never get the output printed.

It's possible that I have to wrap the execution of nonblocking_stuff methods with an EM.run?

EM.run do
   nonblocking_stuff.then { |value| p value }
   nonblocking_stuff.then(proc { |value| p value })
end

Maybe it's just me

Thank you.

Promise.fulfill and Promise.reject shorthands

For now the readme says:

Promise.new
  .tap(&:fulfill)
  .then { Promise.new.tap(&:fulfill) }
  .then { Promise.new.tap(&:reject) }
  .then(nil, proc { |reason| p reason })

Last two PRs I've made introduced a change so following is possible:

Promise.new.fulfill
  .then { Promise.new.fulfill }
  .then { Promise.new.reject }
  .then(nil, proc { |reason| p reason })

What about an extra Promise.reject and Promise.fulfill, so following is possible?

Promise.fulfill
  .then { Promise.fulfill }
  .then { Promise.reject }
  .then(nil, proc { |reason| p reason })

Is it ok?

#sync breaks when mixing Promise classes

I'm running into a bug in promise.rb where the sync method breaks when mixing various Promise classes together.

Here's some sample code demonstrating the problem:

require "promise"

class MyPromise < ::Promise
  def wait
    fulfill(456)
  end
end

p1 = Promise.resolve(123)

p2a = MyPromise.new
p2a.sync

p2b = MyPromise.new

p3a = p1.then { |a| p2a.then { |b| a + b } }
p3b = p1.then { |a| p2b.then { |b| a + b } }

puts p3a.sync
puts p3b.sync

What's happening is that when then is called on p1 (which is already resolved), promise.rb internally creates a new promise of the same type as p1 and then immediately executes the then block. Even though the then block is called immediately and returns a new MyPromise instance, the internal state of the promise returned by the then block is copied into the newly created Promise instance rather than the MyPromise instance being returned directly.

If p2a is also already resolved, this is not a problem and calling p3a.sync returns the right thing.

If p2b is not already resolved when p3b.sync is called, the sync call tries to call wait on an instance of Promise, rather than an instance of MyPromise. This raises a NoMethodError.

The output I'd expect the code sample above to produce is:

579
579

The actual output is:

579
lib/promise.rb:64:in `sync': undefined local variable or method `wait' for #<Promise:0x007fb8db51e028 @state=:pending, @callbacks=[]> (NameError)
    from x.rb:20:in `<main>'

ES6-alike initializer

Do you mind introducing initialize that looks similar to ES6 version?

Promise.new do |resolve, reject|
  # ...
end

Closing my Github account

Hi all,

I'm the original author of promise.rb - it's great to see it's still of use to so many people. I intend to close my Github account and here's a plan how to do that without causing any trouble for promise.rb. These steps can hopefully be done in less than 10 minutes.

  1. Create lgierth2 org
  2. Add all current committers to that org
  3. Move promise.rb to lgierth2 org
  4. Rename lgierth account to something else
  5. Rename lgierth2 org to lgierth
  6. Done

Does this sound good? If so, I'd follow through with this on 1 July.

Thanks!

bundle install fails on this repo

The Gemfile for this repo is using devtools with an unspecified version or git reference. The Gemfile.devtools requires gem 'rspec', '~> 2.99.0' but all the released version of devtools expect 3.x

Here is the error message from bundle install:

Bundler could not find compatible versions for gem "rspec":
  In Gemfile:
    rspec (~> 2.99.0)

    devtools was resolved to 0.1.4, which depends on
      rspec (~> 3.4.0)

    fuubar was resolved to 1.2.1, which depends on
      rspec (~> 2.0)

Ability to set unhandled_rejection callback

Hey!

Your library is awesome, but the promises in my code get often rejected and I don't even know about it.. Could you provide Promise.unhandled_rejection function to handle unhandled rejections (I'd use it in development only)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.