码迷,mamicode.com
首页 > 其他好文 > 详细

封装promise

时间:2018-07-03 14:37:02      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:open   ext   success   state   error   func   ===   pre   xhr   

const getJSON = function(url,type,data) {
const promise = new Promise(function(resolve, reject){
const handler = function() {
if (this.readyState !== 4) {
return;
};
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error(this.statusText));
}
};
const client = new XMLHttpRequest();
client.open(type, url);
client.onreadystatechange = handler;
client.responseType = "json";
if(type==‘get‘){
client.send();
}else {
client.setRequestHeader("Content-Type","application/json");//data只能是JSON字符串
client.send(JSON.stringify(data)) //post请求传入string
}
 
});
return promise;
};
 
 
 
调用案例
$(function() {
  $("button").click(function() {  
     getJSON(‘http://localhost:3000/info‘,‘get‘).then( res => {
      //success
     console.log(‘ok‘);
     }).catch( res=> {
          console.error(‘出错了‘, error);
    });
  });
//JQUERY 1.5.0返回的是xhr对象 高于1.5.0返回的deferred对象
})

封装promise

标签:open   ext   success   state   error   func   ===   pre   xhr   

原文地址:https://www.cnblogs.com/shiapi/p/9257717.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!