Sha256: 018f686688394dedd762e461a0000ba4688d1f10d3b9757f6070486ed517dc8d

Contents?: true

Size: 1.36 KB

Versions: 17

Compression:

Stored size: 1.36 KB

Contents

# Promise

`Promise` is a class available in the Opal stdlib for helping structure asynchronous code.

It can be required inside any Opal applicaton:

```ruby
require 'promise'
```

## Usage

This example shows how to use a `HTTP` request from `opal-jquery` from a callback style, into a promise style handler.

```ruby
def get_json(url)
  promise = Promise.new

  HTTP.get(url) do |response|
    if response.ok?
      promise.resolve response.json
    else
      promise.reject response
    end
  end

  promise
end

get_json('/users/1.json').then do |json|
  puts "Got data: #{json}"
end.fail do |res|
  alert "It didn't work :( #{res}"
end
```

A promise can only be resolved or rejected once.

### Chaining Promises

Promises become useful when chained together. The previous example could be extended to get another object from the result of the first request.

```ruby
get_json('/users/1.json').then do |json|
  get_json("/posts/#{json[:post_id]}.json")
end.then do |post|
  puts "got post: #{post}"
end
```

### Composing Promises

`Promise.when` can be used to wait for more than 1 promise to resolve (or reject). Lets assume we wanted to get 2 different users:

```ruby
first = get_json '/users/1.json'
second = get_json '/users/2.json'

Promise.when(first, second).then do |user1, user2|
  puts "got users: #{user1}, #{user2}"
end.fail do
  alert "Something bad happened"
end
```

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
opal-1.3.1 docs/promises.md
opal-1.3.0 docs/promises.md
opal-1.3.0.rc1 docs/promises.md
opal-1.3.0.alpha1 docs/promises.md
opal-1.2.0 docs/promises.md
opal-1.2.0.beta1 docs/promises.md
opal-1.1.1 docs/promises.md
opal-1.1.1.rc1 docs/promises.md
opal-1.1.0 docs/promises.md
opal-1.1.0.rc1 docs/promises.md
opal-1.0.5 docs/promises.md
opal-1.0.4 docs/promises.md
opal-1.0.3 docs/promises.md
opal-1.0.2 docs/promises.md
opal-1.0.1 docs/promises.md
opal-1.0.0 docs/promises.md
opal-1.0.0.beta1 docs/promises.md