四种异步:
1:同步 代码从上往下执行遇见同步会一直等,等到完成才会继续走
异步 代码从上往下执行 遇见异步 就先走了 异步的代码后面执行
2:说ajax 哪些是异步 定时器 ajax 事件处理(绑定的onclick等) nodejs 读取文件也有异步
console.log(1)
$.ajax({
url:"./php/ok.php",
success:function(res){
console.log(2)
console.log('ajax结果',res)
}
})
console.log(3)
=>>132
3:ajax+promise 解决地域回调 顺便简单封装axios
好处没有那么多嵌套关系,是一个链式编程结果。
let p1 = new Promise(function(resolve,reject){
$.ajax({
url:"./php/ok.php",
success:function(res){
resolve(res)
//console.log('ajax结果',res)
}
})
p1.then(function(data){
console.log(data) //=>ajax的res
let p2=new Promise(function(resolve,reject){
$.ajax({
url:"./php/ok.php",
success:function(res){
resolve(res)
//console.log('ajax结果',res)
}
})
})
return p2
})
.then(function(second){
})
function axios(){
let p1 = new Promise(function(resolve,reject){
$.ajax({
url:"./php/ok.php",
success:function(res){
resolve(res)
//console.log('ajax结果',res)
}
})
return p1
}
//axios()调用axios函数得到p1 new的promise
//axios就是把发送ajax用promise封装了一下
axios().then(function(res){
console.log('结果',res)
})
Promise.all(数组,function)
//第一个参数 数组,
Promise.all([p1,p2,p3...],function)
//必须数组里面的所有的promise执行完毕 才成功
//用在要同时有很多成功的结果的情况
Promise.race([p1,p2,p3...],function)
//只要数组里面的任何一个成功 整个race就成功
4: async await async/await使得异步代码看起来像同步代码,这正是他的魔力所在
async await最简单的使用 就是 可以省略掉then 简单快捷、、
//代码看起来清晰
document.getElementById("btn").onclick = ()=>{
//使用axios,使用。then
axios().then(function(res){
console.log('结果,res')
})
}
document.getElementById("btn").onclick = async ()=>{
let res = await axios() //这里会等待成功 才执行下面
console.log(res)
}
5:async +await 原理 generate+yield 的语法糖
为什么? 方便 代码清晰
async函数是什么?一句话,他是Generator函数的语法糖
Generator函数是ES6提供的一种异步变成解决方案,语法行为与传统函数完全不同。
Generator函数 function* yield暂停标志,使用next执行下一段
//Generator方式的函数 里面的代码是分段执行 看到yield 就给你分一段
function* helloWorldGenerator(){
yield 'hello'; //yield类似暂停标记
yield 'world';
return 'ending'
}
var hw = helloWorldGenerator();//hw返回一个指针
console.log(hw),//这个函数的结果 是ending吗?不是,因为代码是暂停的,是一个暂停标记,指向hello
console.log(hw.next()) //next表示 拿出这个暂停的值 hello
console.log(hw.next()) //world
console.log(hw.next()) //ending
console.log(hw.next()) //undefined