1.这里就简单通过使用promise和原生js来简单封装一下请求
const getJSON = function (url) {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === 4) {
if (this.status === 200) {
resolve(this.response.HeWeather6);
} else {
reject(new Error(this.statusText));
}
}
}
})
}
let a = getJSON('https://free-api.heweather.net/s6/weather/now?location=dalian&key=c56d9631e4b24ccca21a6e096b12c8a4')
.then((data) => {
return data[0]
}).then((obj)=>{
console.log(obj);
})
console.log(a);
then函数小结:
- then() 第一个参数是relove回调函数,第二个参数是可选的 是reject状态回调的函数
- then()返回一个新的promise实例,可以采用链式编程