/*
@url 请求地址
@超时时间
@return promise
*/
var getJSONP = function(url, overtime) {
var promise = new Promise(function(resolve, reject) {
//注册回调函数
var callbackName = 'jsonp'+Math.ceil(Math.random() * 1000000);
window[callbackName] = function(json) {
head.removeChild(script); //移除scipt标签
clearTimeout(script.timer); //清除超时计时器
window[callbackName] = null;
resolve(json); //成功处理
}
//生成scipt标签
var script = document.createElement('script');
script.src = url;
var head = document.getElementsByTagName('head')[0];
head.appendChild(script);
//错误处理
script.onerror = function(){
if(window[callbackName] == null){
reject('timeout'); //超时处理
} else{
reject('faild'); //失败处理
window[callbackName] = null;
head.removeChild(script);
}
}
//超时判断
script.timer = setTimeout(function () {
window[callbackName] = null;
head.removeChild(script);
}, overtime);
});
return promise;
};
网友评论