Skip to content
This repository was archived by the owner on Dec 31, 2018. It is now read-only.

Commit 6da2d03

Browse files
committed
You can add promises as a callback to existing promises
1 parent efbda6a commit 6da2d03

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

index.js

+23-2
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,17 @@
77
*
88
* Once the promise is fulfilled or rejected, the "done" function will be called with the following parameters
99
* done(err, results);
10+
*
11+
* You can pass other promises to "done" and they will get resolved/rejected according to the original promise.
1012
*/
1113
function promise() {
1214
var _results = null;
1315
var _err = null;
1416
var _done = false;
1517
// callbacks
1618
var _cbs = [];
19+
// promises
20+
var _promises = [];
1721

1822
// Calls all callbacks on the list when we're done.
1923
var emptyStack = function() {
@@ -23,6 +27,11 @@ function promise() {
2327
while (cb = _cbs.shift()) {
2428
cb.call(this, _err, _results);
2529
}
30+
31+
while (cb = _promises.shift()) {
32+
if (_err) cb.reject(_err, _results);
33+
else cb.resolve(_results);
34+
}
2635
};
2736

2837
this.resolve = function(results) {
@@ -32,22 +41,34 @@ function promise() {
3241

3342
setImmediate(emptyStack);
3443
};
35-
this.reject = function(err) {
44+
this.reject = function(err, results) {
3645
if (_done) return;
3746

3847
_err = err;
48+
_results = results;
3949

4050
setImmediate(emptyStack);
4151
};
52+
4253
/**
4354
* What to do when the promise has been fulfilled
4455
*/
4556
this.done = function(cb) {
57+
if (cb instanceof promise) {
58+
if (_done) {
59+
if (_err) cb.reject(_err, _results);
60+
else cb.resolve(_results);
61+
}
62+
else
63+
_promises.push(cb);
64+
65+
return(this);
66+
}
4667
if (typeof(cb) !== "function")
4768
throw "callback is not a function";
4869

4970
if (_done)
50-
setImmediate(function() { cb(_err, _results); });
71+
setImmediate(cb, _err, _results);
5172
else
5273
_cbs.push(cb);
5374

0 commit comments

Comments
 (0)