-
Notifications
You must be signed in to change notification settings - Fork 1
/
XHR-Queue.js
86 lines (64 loc) · 1.54 KB
/
XHR-Queue.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
XHR_QUEUE = function(){};
XHR_QUEUE.prototype.add = function(method, url, onSuccess, onError, data){
var reqArg = {
method: method,
url: url,
onSuccess: onSuccess,
onError: onError,
data : data ? data : {}
};
if(this.requests)
this.requests.push(reqArg);
else
this.requests = [reqArg];
return this;
};
XHR_QUEUE.prototype.start = function(callback){
if(callback)
var resArr = [];
var self = this;
var reqLength = this.requests.length;
function ExecuteRequests(i){
if(i === reqLength){ // BASE CASE
self.requests.length = 0; // Clean requests queue
if(callback)
callback(resArr);
else
return ;
}else{ // RECURSIVE CASE
CreateHTTPRequest(
self.requests[i].method,
self.requests[i].url,
function(res){
if(callback)
resArr.push(res);
self.requests[i].onSuccess(res);
ExecuteRequests(i+1);
},
function(res){
if(callback)
resArr.push(res);
self.requests[i].onError(res);
ExecuteRequests(i+1);
},
self.requests[i].data
);
}
};
ExecuteRequests(0); // START RECURSIVE FUNCTION
};
function CreateHTTPRequest(method, url, onSuccess, onError, data){
var xhr = Ti.Network.createHTTPClient();
// Open the HTTP connection
xhr.open(method, url);
// When the connection was successful
xhr.onload = function() {
onSuccess(JSON.parse(this.responseText));
};
// When there was an error
xhr.onerror = function(e) {
onError(e.error);
};
xhr.send(data);
};
module.exports = XHR_QUEUE;