-
Notifications
You must be signed in to change notification settings - Fork 36
/
jsonp.js
34 lines (26 loc) · 798 Bytes
/
jsonp.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
var callbackPrefix = 'MAMA2_HTTP_JSONP_CALLBACK'
var callbackCount = 0
var timeoutDelay = 10000
function callbackHandle () {
return callbackPrefix + callbackCount++
}
function jsonp(url, callbackKey) {
return new Promise((fulfill, reject) => {
callbackKey = callbackKey || 'callback'
var _callbackHandle = callbackHandle()
window[_callbackHandle] = function (rs) {
clearTimeout(timeoutTimer)
delete window[_callbackHandle]
fulfill(rs)
}
var timeoutTimer = setTimeout(function () {
delete window[_callbackHandle]
reject(new Error('jsonp timeout'))
}, timeoutDelay)
var src = url + (url.indexOf('?') >= 0 ? '&' : '?') + callbackKey + '=' + _callbackHandle;
fetch(src).then(res => res.text()).then(res => {
eval(res)
})
})
}
module.exports = jsonp