-
Notifications
You must be signed in to change notification settings - Fork 22
/
promises.js
61 lines (52 loc) · 1.64 KB
/
promises.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
// # module: promises
//
// An implementation of pure promises.
// -- Symbols ----------------------------------------------------------
//
// Used for storing the computation associated with the promise.
var expression = Symbol('computation');
// -- Implementation ---------------------------------------------------
// ### class: Promise(computation)
//
// Constructs a new promise for a particular expression.
function Promise(computation) {
this[expression] = computation;
}
// ### function: resolve(x)
//
// Constructs a new promise with the successful value `x`.
Promise.resolve = function(x) {
return new Promise((resolve, reject) => resolve(x));
};
// ### function: reject(x)
//
// Constructs a new promise with the failure value `x`.
Promise.reject = function(x) {
return new Promise((resolve, reject) => reject(x));
};
// ### function: run(promise, onSuccess, onFailure)
//
// Runs a promise and all of its dependencies.
Promise.run = function(promise, onSuccess, onFailure) {
promise[expression](onSuccess, onFailure);
};
// ### method: then(onSuccess, onFailure)
//
// Transforms the value of a promise.
Promise.prototype.then = function(onSuccess, onFailure) {
return new Promise((resolve, reject) => this.then(
value => Promise.run(onSuccess(value), resolve, reject),
error => Promise.run(onFailure(error), resolve, reject)
));
};
// ### method: catch(onFailure)
//
// Transforms the failure value of a promise.
Promise.prototype.catch = function(onFailure) {
return this.then(
value => Promise.resolve(value),
onFailure
);
};
// -- Exports ----------------------------------------------------------
module.exports = Promise;