This repository has been archived by the owner on Dec 31, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
79 lines (65 loc) · 1.48 KB
/
index.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
'use strict';
/**
* A *very* simple promise
*
* Adapted from: https://github.com/mostlygeek/Node-Simple-Cache
*
* Once the promise is fulfilled or rejected, the "done" function will be called with the following parameters
* done(err, results);
*
* You can pass other promises to "done" and they will get resolved/rejected according to the original promise.
*/
function promise() {
var _results = null;
var _err = null;
var _done = false;
// callbacks
var _cbs = [];
// promises
var _promises = [];
// Calls all callbacks on the list when we're done.
var emptyStack = function() {
_done = true;
var cb;
while (cb = _cbs.shift()) {
cb.call(this, _err, _results);
}
while (cb = _promises.shift()) {
if (_err) cb.reject(_err, _results);
else cb.resolve(_results);
}
};
this.resolve = function(results) {
if (_done) return;
_results = results;
setImmediate(emptyStack);
};
this.reject = function(err, results) {
if (_done) return;
_err = err;
_results = results;
setImmediate(emptyStack);
};
/**
* What to do when the promise has been fulfilled
*/
this.done = function(cb) {
if (cb instanceof promise) {
if (_done) {
if (_err) cb.reject(_err, _results);
else cb.resolve(_results);
}
else
_promises.push(cb);
return(this);
}
if (typeof(cb) !== "function")
throw "callback is not a function";
if (_done)
setImmediate(cb, _err, _results);
else
_cbs.push(cb);
return this;
};
};
module.exports = promise;