-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
49 lines (42 loc) · 1.19 KB
/
index.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
'use strict';
var fetchIsDefined = !!global.fetch;
function timelyPromise(promise, ms) {
var timeout = new Promise((resolve, reject) => {
var id = setTimeout(function() {
clearTimeout(id);
reject(new Error('timeout'));
}, ms);
})
return Promise.race([promise, timeout]);
}
function fetch(uri, options = {}) {
var defaults = {
method: 'GET',
headers: [],
timeout: null
};
var op = Object.assign({}, defaults, options);
var promise = op.onProgress || op.onUploadProgress || !fetchIsDefined ?
new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(op.method, uri);
xhr.onload = function() {
resolve(xhr.responseText);
}
xhr.onerror = reject;
xhr.onprogress = op.onProgress;
xhr.upload.onprogress = op.onUploadProgress;
op.headers.forEach(function(value, name) {
xhr.setRequestHeader(name, value);
})
xhr.send(op.body);
}) : fetch(uri, op);
return op.timeout === null ?
promise :
timelyPromise(promise, op.timeout);
}
module.exports = fetch;
module.exports.timelyPromise = timelyPromise;
if (!fetchIsDefined) {
global.fetch = module.exports;
}