UNPKG

2.77 kBMarkdownView Raw
1[![Build Status](https://travis-ci.org/then/promise.png)](https://travis-ci.org/then/promise)
2<a href="http://promises-aplus.github.com/promises-spec"><img src="http://promises-aplus.github.com/promises-spec/assets/logo-small.png" align="right" /></a>
3# promise
4
5 This a bare bones [Promises/A+](http://promises-aplus.github.com/promises-spec/) implementation.
6
7 It is designed to get the basics spot on correct, so that you can build extended promise implementations on top of it.
8
9## Installation
10
11 Client:
12
13 $ component install then/promise
14
15 Server:
16
17 $ npm install then-promise
18
19## API
20
21 In the example below shows how you can load the promise library (in a way that works on both client and server). It then demonstrates creating a promise from scratch. You simply call `new Promise(fn)`. There is a complete specification for what is returned by this method in [Promises/A+](http://promises-aplus.github.com/promises-spec/). The resolver object has two methods `reject` and `fulfill` and their use is demonstrated here:
22
23```javascript
24var Promise = require('then-promise');
25
26var promise = new Promise(function (resolver) {
27 get('http://www.google.com', function (err, res) {
28 if (err) resolver.reject(err);
29 else resolver.fulfill(res);
30 });
31 });
32```
33
34## Extending Promises
35
36 There are two options for extending the promises created by this library.
37
38### Inheritance
39
40 You can use inheritance if you want to create your own complete promise library with this as your basic starting point, perfect if you have lots of cool features you want to add. Here is an example of a promise library called `Awesome`, which is built on top of `Promise` correctly.
41
42```javascript
43var Promise = require('then-promise');
44function Awesome(fn) {
45 Promise.call(this, fn);
46}
47Awesome.prototype = new Promise();
48Awesome.prototype.constructor = Awesome;
49
50//Awesome extension
51Awesome.prototype.spread = function (cb) {
52 return this.then(function (arr) {
53 return cb.apply(this, arr);
54 })
55};
56```
57
58 N.B. if you fail to set the prototype and constructor properly or fail to do Promise.call, things can fail in really subtle ways.
59
60### Extending the Prototype
61
62 In general, you should never extend the prototype of this promise implimenation because your extensions could easily conflict with someone elses extensions. However, this organisation will host a library of extensions which do not conflict with each other, so you can safely enable any of those. If you think of an extension that we don't provide and you want to write it, submit an issue on this repository and (if I agree) I'll set you up with a repository and give you permission to commit to it.
63
64## License
65
66 MIT