ajax发送请求的原生简单写法
var xhr = new XMLHttpRequest()
xhr.open('get','http://localhost:3000/data1')
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState===4) {
var ret = xhr.responseText
console.log(ret)
}
}
但是这样的话每次调用我们都要重新写一遍,太过冗余,可以封装成函数
将ajax请求操作封装成函数
function ajax (url,callback){
var xhr = new XMLHttpRequest()
xhr.open('get','http://localhost:3000/'+url)
xhr.send()
xhr.onreadystatechange = function(){
if(xhr.readyState===4) {
var ret = xhr.responseText
// 异步结果获取只能用回调函数
callback(ret)
}
}
}
但这样也会造成新的问题,如果多次请求操作,且结果二需要第一次请求的结果时会造成回调地狱,代码的阅读性弱
ajax('data1',function(ret){
console.log(ret)
ajax('data2',function(ret){
console.log(ret)
ajax('data3',function(ret){
console.log(ret)
})
})
})
为了改造上面的回调地狱,诞生了Promise, Promise就是一种语法糖(形式变了,但是功能没变)
function proData (url) {
return new Promise (function(resolve,reject){
var xhr = new XMLHttpRequest()
xhr.open('get','http://localhost:3000/'+url)
xhr.send()
xhr.onreadystatechange = function() {
if(xhr.readyState===4) {
resolve(xhr.responseText)
}
}
})
}
proData('data1')
.then(ret=>{
console.log(ret)
return proData('data2')
})
.then(ret=>{
console.log(ret)
return proData('data3')
})
.then(ret=>{
console.log(ret)
})
.then(()=>{
console.log('123')
})
注意点:
如果在then方法中没有返回Promise实例对象,那么下一个then由默认产生的Promise实例对象调用, 如果在then中显示的返回一个具体数据,那么下一个then可以获取该数据
引入promise后阅读性增强,但是代码还是不够简洁,
所以有出现了async和await
async function getData (){
// 将异步操作写成同步的写法
var ret1 = await proData('data1')
var ret2 = await proData('data2')
var ret3 = await proData('data3')
console.log(ret1)
console.log(ret2)
console.log(ret3)
}
getData()
本文从原生Ajax请求开始,逐步介绍了如何通过封装函数简化请求过程,进而讨论了Promise如何解决回调地狱的问题,最后引入了Async/Await,使异步代码看起来更像同步代码,提高了代码的可读性和维护性。
1102

被折叠的 条评论
为什么被折叠?



