针对于Promise专栏一,在promise专栏二中有三个重点需要掌握
第一个是 原生ajax请求的过程
第二个是 promise封装ajax请求发送的过程
第三个是 async和await对于使用promise对象封装ajax请求的优化过程
第一:原生ajax请求的过程
// //axios只是基于原生ajax封装的的一个js工具 // // 原生发送ajax请求(get请求) // // 1.创建一个xhr对象 // const xhr = new XMLHttpRequest() // // 2.打开链接的时候是可以设置我们的请求方式和请求地址链接 // xhr.open('get','http://localhost:3000/list') // // 3.发送请求 由于是get请求 没有请求体 // xhr.send(null) // // 4.监听xhr状态 处理响应 // xhr.onreadystatechange = function(){ // if(xhr.readyState === 4){ // if(xhr.status === 200){ // console.log(JSON.parse(xhr.responseText)); // }else{ // console.log(xhr.responseText); // } // } // }
第二:使用promise封装原生ajax请求的过程
//使用promise封装ajax请求的过程 //一旦promise对象创建完成,就会立即发送ajax请求 function axios(option){ return new Promise((resolve,reject)=>{ // 1.创建一个xhr对象 const xhr = new XMLHttpRequest() // 2.打开链接的时候是可以设置我们的请求方式和请求地址链接 xhr.open(option.method,option.url) // 3.发送请求 由于是get请求 没有请求体 xhr.send(null) // 4.监听xhr状态 处理响应 xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status === 200){ resolve(JSON.parse(xhr.responseText)); }else{ reject(xhr.responseText); } } } }) } axios({ method:'get', url:'http://localhost:3000/list' }).then(res=>{console.log(res)})
第三:async和await对于使用promise对象封装ajax请求的优化的过程
<script> //promse对象封装ajax请求 function axios(option){ return new Promise((resolve,reject)=>{ //原生ajax请求 const xhr = new XMLHttpRequest() xhr.open(option.method,option.url) xhr.send(null) xhr.onreadystatechange = function(){ if(xhr.readyState === 4){ if(xhr.status === 200){ resolve(JSON.parse(xhr.responseText)); }else{ reject(xhr.responseText); } } } }) } // async和await对于使用promise对象的优化过程 async function fn(){ const res = await axios({method:'get',url:'http://localhost:3000/list'}) console.log(res); } fn() </script>