ES6精讲12-使用promise封装请求

303 阅读1分钟

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');
        // 发送send
        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) => {
             // console.log(data);
             return data[0]  //return的值会被后面then接收到
         }).then((obj)=>{
             console.log(obj);
         })
     
console.log(a);//这里会发现,then返回的是一个promise对象;

then函数小结:

  • then() 第一个参数是relove回调函数,第二个参数是可选的 是reject状态回调的函数
  • then()返回一个新的promise实例,可以采用链式编程