Giter Club home page Giter Club logo

when.js's Introduction

Please Note: this project has moved from briancavalier/when to cujojs/when. Any existing forks have been automatically moved to cujojs/when. However, you'll need to update your clone and submodule remotes manually.

Update the url in your .git/config, and also .gitmodules for submodules:

git://github.com/cujojs/when.git
https://[email protected]/cujojs/when.git

Helpful link for updating submodules: Git Submodules: Adding, Using, Removing, Updating


A lightweight CommonJS Promises/A and when() implementation. It also provides several other useful Promise-related concepts, such as joining and chaining, and has a robust unit test suite.

It's just over 1k when compiled with Google Closure (w/advanced optimizations) and gzipped.

when.js was derived from the async core of wire.js.

What's New?

v0.11.1

  • Added when/apply helper module for using arguments-based and variadic callbacks with when.all, when.some, when.map, or any promise that resolves to an array. (#14)
  • .then(), when(), and all other methods that accept callback/errback/progress handlers will throw if you pass something that's not a function. (#15)

v0.11.0

  • when.js now assimilates thenables that pass the Promises/A duck-type test, but which may not be fully Promises/A compliant, such as jQuery's Deferred and curl's global API (See the API at a glance section)
    • when(), and when.all/some/any/map/reduce/chain() are all now guaranteed to return a fully Promises/A compliant promise, even when their input is not compliant.
    • Any non-compliant thenable returned by a callback or errback will also be assimilated to protect subsequent promises and callbacks in a promise chain, and preserve Promises/A forwarding guarantees.

v0.10.4

  • Important Fix for some AMD build/optimizer tools: Switching back to more verbose, builder-friendly boilerplate
    • If you are using when.js 0.10.3 with the dojo or RequireJS build tools, you should update to v.10.4 as soon as possible.

v0.10.3

Warning: This version will not work with most AMD build tools. You should update to 0.10.4 as soon as possible.

  • Minor package.json updates
  • Slightly smaller module boilerplate

v0.10.2

  • Performance optimizations for when.map() (thanks @smitranic), especially for large arrays where the mapFunc is also async (i.e. returns a promise)
  • when.all/some/any/map/reduce handle sparse arrays (thanks @rwaldrn)
  • Other minor performance optimizations

v0.10.1

  • Minor tweaks (thanks @johan)
    • Add missing semis that WebStorm didn't catch
    • Fix DOH submodule ref, and update README with info for running unit tests

v0.10.0

  • when.map and when.reduce - just like Array.map and Array.reduce, but they operate on promises and arrays of promises
  • Lots of internal size and performance optimizations
  • Still only 1k!

v0.9.4

  • Important fix for break in promise chains

Examples

Check the wiki for examples

API

when()

Register a handler for a promise or immediate value:

when(promiseOrValue, callback, errback, progressback)

// Always returns a promise, so can be chained:

when(promiseOrValue, callback, errback, progressback).then(anotherCallback, anotherErrback, anotherProgressback)

when.defer()

Create a new Deferred containing separate promise and resolver parts:

var deferred = when.defer();

var promise = deferred.promise;
var resolver = deferred.resolver;

The deferred has the full promise + resolver API:

deferred.then(callback, errback, progressback);
deferred.resolve(value);
deferred.reject(reason);
deferred.progress(update);

The promise API:

// var promise = deferred.promise;
promise.then(callback, errback, progressback);

The resolver API:

// var resolver = deferred.resolver;
resolver.resolve(value);
resolver.reject(err);
resolver.progress(update);

when.isPromise()

var is = when.isPromise(anything);

Return true if anything is truthy and implements the then() promise API. Note that this will return true for both a deferred (i.e. when.defer()), and a deferred.promise since both implement the promise API.

when.some()

when.some(promisesOrValues, howMany, callback, errback, progressback)

Return a promise that will resolve when howMany of the supplied promisesOrValues have resolved. The resolution value of the returned promise will be an array of length howMany containing the resolutions values of the triggering promisesOrValues.

when.all()

when.all(promisesOrValues, callback, errback, progressback)

Return a promise that will resolve only once all the supplied promisesOrValues have resolved. The resolution value of the returned promise will be an array containing the resolution values of each of the promisesOrValues.

when.any()

when.any(promisesOrValues, callback, errback, progressback)

Return a promise that will resolve when any one of the supplied promisesOrValues has resolved. The resolution value of the returned promise will be the resolution value of the triggering promiseOrValue.

when.chain()

when.chain(promiseOrValue, resolver, optionalValue)

Ensure that resolution of promiseOrValue will complete resolver with the completion value of promiseOrValue, or instead with optionalValue if it is provided.

Returns a new promise that will complete when promiseOrValue is completed, with the completion value of promiseOrValue, or instead with optionalValue if it is provided.

Note: If promiseOrValue is not an immediate value, it can be anything that supports the promise API (i.e. then()), so you can pass a deferred as well. Similarly, resolver can be anything that supports the resolver API (i.e. resolve(), reject()), so a deferred will work there, too.

when.map()

when.map(promisesOrValues, mapFunc)

Traditional map function, similar to Array.prototype.map(), but allows input to contain promises and/or values, and mapFunc may return either a value or a promise.

The map function should have the signature:

mapFunc(item)

Where:

  • item is a fully resolved value of a promise or value in promisesOrValues

when.reduce()

when.reduce(promisesOrValues, reduceFunc, initialValue)

Traditional reduce function, similar to Array.prototype.reduce(), but input may contain promises and/or values, and reduceFunc may return either a value or a promise, and initialValue may be a promise for the starting value.

The reduce function should have the signature:

reduceFunc(currentValue, nextItem, index, total)

Where:

  • currentValue is the current accumulated reduce value
  • nextItem is the fully resolved value of the promise or value at index in promisesOrValues
  • index the basis of nextItem ... practically speaking, this is the array index of the promiseOrValue corresponding to nextItem
  • total is the total number of items in promisesOrValues

when/apply

function functionThatAcceptsMultipleArgs(array) {
    // ...
}

var functionThatAcceptsAnArray = apply(functionThatAcceptsMultipleArgs);

Helper that allows using callbacks that take multiple args, instead of an array, with when.all/some/map:

when.all(arrayOfPromisesOrValues, apply(functionThatAcceptsMultipleArgs));

See the wiki for more info and examples.

Testing

To run the unit tests, from the when.js dir:

  1. git submodule init
  2. git submodule update
  3. Open test.index.html in your browser

References

Much of this code is based on @unscriptable's tiny promises, the async innards of wire.js, and some gists here, here, here, and here

Some of the code has been influenced by the great work in Q, Dojo's Deferred, and uber.js.

when.js's People

Contributors

briancavalier avatar johan avatar rwaldron avatar scothis avatar smitranic avatar

Stargazers

Allex avatar

Watchers

Allex avatar James Cloos avatar  avatar

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.