7
7
*
8
8
* Once the promise is fulfilled or rejected, the "done" function will be called with the following parameters
9
9
* done(err, results);
10
+ *
11
+ * You can pass other promises to "done" and they will get resolved/rejected according to the original promise.
10
12
*/
11
13
function promise ( ) {
12
14
var _results = null ;
13
15
var _err = null ;
14
16
var _done = false ;
15
17
// callbacks
16
18
var _cbs = [ ] ;
19
+ // promises
20
+ var _promises = [ ] ;
17
21
18
22
// Calls all callbacks on the list when we're done.
19
23
var emptyStack = function ( ) {
@@ -23,6 +27,11 @@ function promise() {
23
27
while ( cb = _cbs . shift ( ) ) {
24
28
cb . call ( this , _err , _results ) ;
25
29
}
30
+
31
+ while ( cb = _promises . shift ( ) ) {
32
+ if ( _err ) cb . reject ( _err , _results ) ;
33
+ else cb . resolve ( _results ) ;
34
+ }
26
35
} ;
27
36
28
37
this . resolve = function ( results ) {
@@ -32,22 +41,34 @@ function promise() {
32
41
33
42
setImmediate ( emptyStack ) ;
34
43
} ;
35
- this . reject = function ( err ) {
44
+ this . reject = function ( err , results ) {
36
45
if ( _done ) return ;
37
46
38
47
_err = err ;
48
+ _results = results ;
39
49
40
50
setImmediate ( emptyStack ) ;
41
51
} ;
52
+
42
53
/**
43
54
* What to do when the promise has been fulfilled
44
55
*/
45
56
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
+ }
46
67
if ( typeof ( cb ) !== "function" )
47
68
throw "callback is not a function" ;
48
69
49
70
if ( _done )
50
- setImmediate ( function ( ) { cb ( _err , _results ) ; } ) ;
71
+ setImmediate ( cb , _err , _results ) ;
51
72
else
52
73
_cbs . push ( cb ) ;
53
74
0 commit comments