forked from stackp/promisejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise.js
323 lines (288 loc) · 8.91 KB
/
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*
* Copyright 2012-2013 (c) Pierre Duquesne <stackp@online.fr>
* Licensed under the New BSD License.
* https://github.com/stackp/promisejs
*/
/** @module promise */
(function (exports) {
/**
* @constructor
* @alias module:promise.Promise
*/
function Promise() {
this._callbacks = [];
this._isdone = false;
this.result = [];
}
/**
* @private
*/
Promise.prototype.resolve = function () {
this.result = arguments;
this._isdone = true;
for (var i = 0; i < this._callbacks.length; i++) {
this._callbacks[i].apply(null, this.result);
}
this._callbacks.length = 0;
}
/**
* Resolves a Promise object and calls any callbacks
* with the given arguments
* @returns {Promise}
*/
Promise.prototype.done = function () {
this.resolve.apply(this, arguments);
return this;
}
/**
* Adds callback to the Promise object
* @param {Function} callback
* @param {Promise} [context]
* @returns {Promise} that is resolved when the callback resolves its promise
*/
Promise.prototype.then = function (callback, context) {
var p = new Promise();
function resolve() {
var result = callback.apply(context, arguments);
if (result instanceof Promise) {
result.then(p.resolve, p);
}
else {
p.resolve(result);
}
}
this._isdone
? resolve.apply(null, this.result)
: this._callbacks.push(resolve);
return p;
}
/**
* The callback will be passed an array containing the values passed by each promise,
* in the same order that the promises were given
* @alias module:promise.join
* @param {Promise[]} promises
* @returns {Promise} that is resolved once all the arguments are resolved
*/
function join(promises) {
var p = new Promise();
var results = [];
var resolved = 0;
promises && promises.length > 0
? promises.forEach(notify)
: p.resolve(results);
function notify(pp, i, ps) {
pp.then(function () {
resolved++;
results[i] = Array.prototype.slice.call(arguments);
if (resolved == ps.length) {
p.resolve(results);
}
});
}
return p;
}
/**
* Chains asynchronous functions that return a promise each
* @alias module:promise.chain
* @param {Function[]} callbacks
* @param {Array} [args]
* @returns {Promise} that is resolved once all the arguments are resolved
*/
function chain(callbacks, args) {
var p = new Promise();
if (callbacks && callbacks.length) {
callbacks[0].apply(null, args).then(function (error, result) {
chain(callbacks.slice(1), arguments).then(
function () {
p.resolve.apply(p, arguments);
}
);
});
}
else {
p.resolve.apply(p, args);
}
return p;
}
/* AJAX requests */
/**
* Encodes data in accordance with the content type
* Strings and FormData objects are returned unchanged
* @param {*} data
* @param {string} [type]
* @returns {(string|FormData)}
*/
function encode(data, type) {
if (data instanceof FormData) {
return data;
}
if (typeof data != 'object' || data === null) {
return data || '';
}
switch (type) {
case 'application/json':
return JSON.stringify(data);
case 'text/plain':
return Object.keys(data).map(
function (name) {
return name + '=' + data[name];
}
).join('\r\n');
default/* application/x-www-form-urlencoded */:
return Object.keys(data).map(
function (name) {
return encodeURIComponent(name) + '=' + encodeURIComponent(data[name]);
}
).join('&');
}
}
/**
* @returns {(XMLHttpRequest|ActiveXObject)}
* @throws Unable to create ActiveXObject
*/
function new_xhr() {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
}
return xhr;
}
/**
* @alias module:promise.ajax
* @param {string} method
* @param {string} url
* @param {*} [data]
* @param {Object} [headers]
* @returns {Promise}
*/
function ajax(method, url, data, headers) {
var p = new Promise();
var xhr, payload = null;
try {
xhr = new_xhr();
}
catch (e) {
p.resolve(promise.ENOXHR, '');
return p;
}
// List of content types which can be used
// to encode data if Content-Type header matches one of them
// The first one is used by default
var supportedTypes = [
'application/x-www-form-urlencoded',
'application/json',
'text/plain'
];
// Content-Type of the current request
// or default value if not specified
var contentType = (
headers && headers[Object.keys(headers).filter(
function (h) {
return h.toLowerCase() == 'content-type';
}
)[0]]
) || supportedTypes[0];
// GET request data is always urlencoded and attached to the url
if (method.toUpperCase() == 'GET') {
xhr.open(method, url + (data ? '?' + encode(data) : ''));
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
// FormData object sets Content-Type to multipart/form-data
// custom Content-Type header should be ignored
else if (data instanceof FormData) {
xhr.open(method, url);
payload = data;
}
// User-defined Content-Type or default value is used
// Data is encoded depending on Content-Type
// which is matched with one of the supported
else {
xhr.open(method, url);
xhr.setRequestHeader('Content-Type', contentType);
payload = encode(data, supportedTypes.filter(
function (type) {
return contentType.match(new RegExp(type, 'i'));
}
)[0]);
}
for (var h in headers) {
if (headers.hasOwnProperty(h) && h.toLowerCase() != 'content-type') {
xhr.setRequestHeader(h, headers[h]);
}
}
function onTimeout() {
xhr.abort();
p.resolve(promise.ETIMEOUT, '', xhr);
}
var timeout = promise.ajaxTimeout;
if (timeout) {
var tid = setTimeout(onTimeout, timeout);
}
xhr.onreadystatechange = function () {
if (timeout) {
clearTimeout(tid);
}
if (xhr.readyState == 4) {
var err = (
!xhr.status ||
(xhr.status < 200 || xhr.status >= 300) &&
xhr.status !== 304
);
p.resolve(err, xhr.responseText, xhr);
}
}
xhr.send(payload);
return p;
}
/**
* @param {string} method
* @returns {Function}
*/
function _ajaxer(method) {
return function (url, data, headers) {
return ajax(method, url, data, headers);
}
}
var promise = {
Promise: Promise,
join: join,
chain: chain,
ajax: ajax,
encode: encode,
get: _ajaxer('GET'),
post: _ajaxer('POST'),
put: _ajaxer('PUT'),
put: _ajaxer('PATCH'),
del: _ajaxer('DELETE'),
/* Error codes */
ENOXHR: 1,
ETIMEOUT: 2,
/**
* Configuration parameter: time in milliseconds after which a
* pending AJAX request is considered unresponsive and is
* aborted. Useful to deal with bad connectivity (e.g. on a
* mobile network). A 0 value disables AJAX timeouts.
*
* Aborted requests resolve the promise with a ETIMEOUT error
* code.
*/
ajaxTimeout: 0
}
if (typeof define === 'function' && define.amd) {
/* AMD support */
define(function () {
return promise;
});
}
else {
exports.promise = promise;
}
})(this);