首页 > 其他 > 详细

封装promise

时间:2018-07-03 13:47:22      阅读:181      评论:0      收藏:0      [点我收藏+]
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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!