Skip to content

ef-labs/when.java

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

When.java

When.java is a Java implementation of the CommonJS Promises/A specification.

It is a port of cujojs/when v3.2.3 by Brian Cavalier and John Hann.

Build Status Maven Central

Getting started

Add a maven dependency to when.java

    <dependency>
      <groupId>com.englishtown</groupId>
      <artifactId>when.java</artifactId>
      <version>3.1.1</version>
    </dependency>

Examples

1. The most basic scenario

The following demonstrates registering a resolution handler that is triggered in the future.

        // Create the when and deferred objects
        When when = WhenFactory.createAsync();
        Deferred<Integer> d = when.defer();

        // Register on fulfilled callback
        Promise<Integer> p = d.getPromise();
        p.then(value -> {
                // Do something
                return null;
        });

        // Use the resolver to trigger the callback registered above.
        // The callback value will be 10
        d.resolve(10);

2. Chaining callbacks

The following demonstrates chaining resolution handlers and how the value can be modified.

        // Create the when and deferred objects
        When when = WhenFactory.createAsync();
        CountDownLatch latch = new CountDownLatch(1);

        Deferred<Integer> d = when.defer();
        Promise<Integer> p = d.getPromise();

        p.then(value -> {
            return when.resolve(2 * value);
        }).then(value2 -> {
            // Do something
            assertEquals(20, value2.intValue());
            return when.resolve(String.valueOf(value2));
        }).then(value3 -> {
            assertEquals("20", value3);
            latch.countDown();
            return null;
        });

        // Use the resolver to trigger the callbacks registered above.
        // The first callback value will be Integer 10
        // The second callback value will be Integer 20
        // The third callback value will be String "20"
        d.resolve(10);