前端知识回顾 ajax promise axios async await
ajax请求数据
//会造成回调地狱
$.ajax({
url:"dizhi"
success(res){
console.log(res)
$.ajax({
url:"dizhi"
success(res){
console.log(res)
}
})
}
})
promise语法
let p1=new Promise(function(resolve,reject){ }固定写法
let p1=new Promise(function(resolve,reject){
resolve(res)//调用then里面的成功的函数 可以传递一个实参
/*
上面的resolve(res)调用then里面的函数相当于
resolve(res){
console.log("成功的函数",res)
}
*/
}).then(fuction(res){
console.log("成功的函数",res) //定义成功的函数,可以接收一个参数
},fuction(){
console.log("失败的函数")
})
ajax 与promise和解决请求回调地狱
在promise里面调用ajax,在ajaxl里面调用promise的成功的函数
let p1=new Promise(function(resolve,reject){
$.ajax({
url:"dizhi"
success(res){ // 请求成功的函数的数据
resolve(res)
}
})
}).then(fuction(res){ //只有.then()之后才会拿到数据 不然p1就是个promise
console.log("成功的函数",res) //定义成功的函数,可以接收一个参数
let p2=new Promise(function(resolve,reject){
$.ajax({
url:"dizhi"
success(res){ // 请求成功的函数的数据
resolve(res)
}
})
return p2
})
}.then(fuction(res){
console.log("成功的函数",res)}
)
封装axios函数
function axios() {
reuturn new Promise(function(resolve,reject){
$.ajax({
url:"dizhi"
success(res){ // 请求成功的函数的数据
resolve(res)
}
})
axions返回一个promise
}
axios() .then(res){
conlose
}
async await 使用
function axios() {
reuturn new Promise(function(resolve,reject){
$.ajax({
url:"dizhi"
success(res){ // 请求成功的函数的数据
resolve(res)
}
})
axions返回一个promise
}
document. getElementById( "btn") . onclick= async()=>{
//使用axios
// axios(). then(function(res){
// console.1og('结果' ,res)
// })
let res=await axios();// 这里会等待成功才执行下面
console.log( '结果' ,res ) //省略了then的步骤 直接拿出返回值 让代码变得和同步一样
}
async awaite 原理
// Generator 函数是ES6 提供的一种异步编程解决方案,语法行为与传统函数完全不同。本章详细介绍Ge
//执行Generator函数会返回一个遍历器对象,也就是说,Generator函数除了状态机,还是-个遍历器)
//形式上,Generator函数是一个普通函数,
//但是有两个特征。是,function关键 字与函数名之间有一个星 号;二:是,函数体内部使用yield表达式,
//重点就一点async TFawait 原理是generate + yield 的语法糖
//async +await 其实就是generate + yield的写法
//为什么要有async +await 因为方便看起米代码清晰
// Generator方 式的函数里面的代码是分段执行看到yield 就给你分一段
function* he lloWorldGenerator() {
yield 'hello'; // yield类似暂停标记
yield " world';
return' ending ;
}
var hw = helloWorldGenerator();//hw 返回一个
// console.log(hw);// 这个函数的结果是ending吗? 不是因为代码是哲停的是一个哲停标记
console. log(hw.next()) ;//next 表示拿出这个哲停的值 hello
console. log(hw. next()) // world
console. log(hw. next()) //ending
console. log(hw . next()) //undefind