(_url)
| 1205 | } |
| 1206 | |
| 1207 | function fetchJsonp(_url) { |
| 1208 | var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; |
| 1209 | |
| 1210 | // to avoid param reassign |
| 1211 | var url = _url; |
| 1212 | var timeout = options.timeout || defaultOptions.timeout; |
| 1213 | var jsonpCallback = options.jsonpCallback || defaultOptions.jsonpCallback; |
| 1214 | |
| 1215 | var timeoutId = undefined; |
| 1216 | |
| 1217 | return new Promise(function (resolve, reject) { |
| 1218 | var callbackFunction = options.jsonpCallbackFunction || generateCallbackFunction(); |
| 1219 | var scriptId = jsonpCallback + '_' + callbackFunction; |
| 1220 | |
| 1221 | window[callbackFunction] = function (response) { |
| 1222 | resolve({ |
| 1223 | ok: true, |
| 1224 | // keep consistent with fetch API |
| 1225 | json: function json() { |
| 1226 | return Promise.resolve(response); |
| 1227 | } |
| 1228 | }); |
| 1229 | |
| 1230 | if (timeoutId) clearTimeout(timeoutId); |
| 1231 | |
| 1232 | removeScript(scriptId); |
| 1233 | |
| 1234 | clearFunction(callbackFunction); |
| 1235 | }; |
| 1236 | |
| 1237 | // Check if the user set their own params, and if not add a ? to start a list of params |
| 1238 | url += url.indexOf('?') === -1 ? '?' : '&'; |
| 1239 | |
| 1240 | var jsonpScript = document.createElement('script'); |
| 1241 | jsonpScript.setAttribute('src', '' + url + jsonpCallback + '=' + callbackFunction); |
| 1242 | jsonpScript.id = scriptId; |
| 1243 | document.getElementsByTagName('head')[0].appendChild(jsonpScript); |
| 1244 | |
| 1245 | timeoutId = setTimeout(function () { |
| 1246 | reject(new Error('JSONP request to ' + _url + ' timed out')); |
| 1247 | |
| 1248 | clearFunction(callbackFunction); |
| 1249 | removeScript(scriptId); |
| 1250 | }, timeout); |
| 1251 | }); |
| 1252 | } |
| 1253 | |
| 1254 | // export as global function |
| 1255 | /* |
no test coverage detected