forked from ondras/my-mind
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise-addons.js
87 lines (80 loc) · 1.97 KB
/
promise-addons.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
/**
* Wait for all these promises to complete. One failed => this fails too.
*/
Promise.all = Promise.when = function(all) {
var promise = new this();
var counter = 0;
var results = [];
for (var i=0;i<all.length;i++) {
counter++;
all[i].then(function(index, result) {
results[index] = result;
counter--;
if (!counter) { promise.fulfill(results); }
}.bind(null, i), function(reason) {
counter = 1/0;
promise.reject(reason);
});
}
return promise;
}
/**
* Promise-based version of setTimeout
*/
Promise.setTimeout = function(ms) {
var promise = new this();
setTimeout(function() { promise.fulfill(); }, ms);
return promise;
}
/**
* Promise-based version of addEventListener
*/
Promise.event = function(element, event, capture) {
var promise = new this();
var cb = function(e) {
element.removeEventListener(event, cb, capture);
promise.fulfill(e);
}
element.addEventListener(event, cb, capture);
return promise;
}
/**
* Promise-based wait for CSS transition end
*/
Promise.transition = function(element) {
if ("transition" in element.style) {
return this.event(element, "transitionend", false);
} else if ("webkitTransition" in element.style) {
return this.event(element, "webkitTransitionEnd", false);
} else {
return new this().fulfill();
}
}
/**
* Promise-based version of XMLHttpRequest::send
*/
Promise.send = function(xhr, data) {
var promise = new this();
xhr.addEventListener("readystatechange", function(e) {
if (e.target.readyState != 4) { return; }
if (e.target.status.toString().charAt(0) == "2") {
promise.fulfill(e.target);
} else {
promise.reject(e.target);
}
});
xhr.send(data);
return promise;
}
Promise.worker = function(url, message) {
var promise = new this();
var worker = new Worker(url);
Promise.event(worker, "message").then(function(e) {
promise.fulfill(e.data);
});
Promise.event(worker, "error").then(function(e) {
promise.reject(e.message);
});
worker.postMessage(message);
return promise;
}