This repository was archived by the owner on Sep 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPromise.js
More file actions
67 lines (55 loc) · 1.79 KB
/
Promise.js
File metadata and controls
67 lines (55 loc) · 1.79 KB
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
/*jshint indent:4, browser:true, strict:false */
/**
* @author Jaime Vega (jhuesos@gmail.com)
* @license MIT License
*/
(function () {
var Promise = function () {
if (!this instanceof Promise) {
return new Promise(arguments);
}
this._queue = [];
return this;
};
/**
* Chain operations depending bases upon state change in of our promises. Both callbacks expects to be called with
* one parameter, the value obtained after the operation was finished. Promise support add multiple then
* @param {Function} [onResolved] Callback to call if the operation was resolved.
* @param {Function} [onRejected] Callback to call if the operation was rejected.
* @return {Promise} Return the object itself to cascade calls.
*/
Promise.prototype.then = function (onResolved, onRejected) {
var callbacks = {
resolvedCB : onResolved,
rejectedCB : onRejected
};
this._queue.push(callbacks);
return this;
};
/**
* Set the promise as resolved and call resolved callback with an argument
* @param {*} arg Argument to pass to the callback
* @return {Promise} Return the object itself to cascade calls.
*/
Promise.prototype.resolve = function (arg) {
var cbs = this._queue.shift();
if (cbs && typeof cbs.resolvedCB === 'function') {
cbs.resolvedCB(arg);
}
return this;
};
/**
* Set the promise as rejected and call rejected callback with an argument
* @param {*} arg Argument to pass to the callback.
* @return {Promise} Return the object itself to cascade calls.
*/
Promise.prototype.reject = function (arg) {
var cbs = this._queue.shift();
if (cbs && typeof cbs.rejectedCB === 'function') {
cbs.rejectedCB(arg);
}
return this;
};
// Export Promise to global scope
window.Promise = Promise;
}());