-
Notifications
You must be signed in to change notification settings - Fork 41
/
turing.promise.js
98 lines (86 loc) · 2.07 KB
/
turing.promise.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/*!
* Turing Promise
* Copyright (C) 2010-2011 Alex R. Young
* MIT Licensed
*/
/**
* The Turing Promise module.
*/
define('turing.promise', ['turing.core'], function(turing) {
function PromiseModule(global) {
/**
* The Promise class.
*/
function Promise() {
var self = this;
this.pending = [];
/**
* Resolves a promise.
*
* @param {Object} A value
*/
this.resolve = function(result) {
self.complete('resolve', result);
},
/**
* Rejects a promise.
*
* @param {Object} A value
*/
this.reject = function(result) {
self.complete('reject', result);
}
}
Promise.prototype = {
/**
* Adds a success and failure handler for completion of this Promise object.
*
* @param {Function} success The success handler
* @param {Function} success The failure handler
* @returns {Promise} `this`
*/
then: function(success, failure) {
this.pending.push({ resolve: success, reject: failure });
return this;
},
/**
* Runs through each pending 'thenable' based on type (resolve, reject).
*
* @param {String} type The thenable type
* @param {Object} result A value
*/
complete: function(type, result) {
while (this.pending[0]) {
this.pending.shift()[type](result);
}
}
};
/**
* Chained Promises:
*
* global().delay(1000).then(function() {
* assert.ok((new Date()).valueOf() - start >= 1000);
* });
*
*/
var chain = {};
turing.init(function() {
if (arguments.length === 0)
return chain;
});
chain.delay = function(ms) {
var p = new turing.Promise();
setTimeout(p.resolve, ms);
return p;
};
global.Promise = Promise;
}
if (typeof module !== 'undefined') {
module.exports = function(t) {
return PromiseModule(t);
}
} else {
PromiseModule(turing);
}
return turing.Promise;
});