promises-a

A bare bones implementation of Promises/A intended to pass https://github.com/domenic/promise-tests while being as small as possible

npm install promises-a
2 downloads in the last day
18 downloads in the last week
46 downloads in the last month

Build Status

promises-a

A bare bones implementation of Promises/A intended to pass all promise-tests while being as small as possible.

This is intended to serve as a base for you to build your own promises libraries, which would typically be expected to provide all sorts of useful helpers. Promises created by this library (or any library based off of this) should be compatable with such helpers, but helpers won't ever be included in this library.

Installation

Client:

$ component install ForbesLindesay/promises-a

Server:

$ npm install promises-a

Alternatively you can download it from the downloads area and reference it with a script tag:

<script src="promises.min.js"></script>

then just refer to it as the global: promises

Usage

Here is an example of how to create a promises function to wrap a low level api, and provide a timeout

var promise = require('promises-a');
function loadDataAsync(id, timeout) {
  timeout = timeout == null ? 500 : timeout;
  var def = promise();

  callLowLevelAPI(id, function (err, res) {
    if (err) return def.reject(err);
    def.resolve(res);
  });

  if (timeout) {
    setTimeout(function () {
      def.reject(new Error('Operation Timed Out (' + timeout + 'ms)'));
    }, timeout);
  }

  return def.promise;
}

Because the promise can only be resolved once, the rejection will be ignored if the operation is successful within the timeout. A timeout of 0 will also be treated as infinite.

API

promise()

Return a new deferred.

deferred

deferred#promise

Get the promise represented by the deferred. This is just an object with a function called then.

deferred#fulfill(value)

Put the promise in a resolved state and fulfill it with the value provided.

deferred#reject(error)

Put the promise in a resolved state and reject it with the error provided.

promise

promise#then(callback, errback)

You can call then with tow optional args. The callback is called when the promise is fulfilled, the errback is called when the promise is rejected. Then also returns a fresh promise which is set to the result of the callback or errback. If you want to forward a rejection either make errback null, or re-throw the error in errback.

If you return a promise from callback or errback it will be resolved before being set as the result of the promise.

promise#done(callback, errback)

Equivalent to calling then, except you don't get a new promise out and exceptions are never swallowed.

License

MIT

npm loves you