jsonp的promise封裝

weixin_34214500發表於2017-09-22
/*
    @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;
};

相關文章