Promise 封装ajax

var getJSON = url=>{
var promise = new Promise((resolve,reject)=>{
    var client = new   XMLHttpRequest()
  client.open("GET",url);
  client.onreadystatechange = hander;
  client.responseType = "json"
  client.setRequesHeader("Accept","application/json");
  client.send()
  function handler(){
    if(this.readyState!==4){
    return ;
}
if(this.status===200){
  resolve(this.response)
}else {
  reject(new Error(this.statusText))
}
}
})
return promise
}

getJSON("/posts.json").then((json)=>{
    console.log(json)
},(error)=>{
  console.log(error)
})

你可能感兴趣的:(Promise 封装ajax)