这里介绍 五种方法(说白了本质 就三种)
1.callback回调函数
function getData(callback){
setTimeout(()=>{
let name = '哈哈哈,我是callback回调函数 获取异步方法里面的数据';
callback(name)
},1000)
}
getData(data=>{
console.log(data)
})
2. promise来处理异步 // resolve成功的回调函数 // reject失败的回调函数
var p = new Promise((resolve,reject)=>{ //ajax setTimeout(()=>{ let n = Math.random() if(n<0.5){ resolve(n) }else{ reject(`${n}大于了0.5所以失败`) } //三元表达式写法 Math.random()<0.5?resolve(n):reject(`${n}大于了0.5所以失败`) },2000) }) p.then((data)=>{ console.log(`${data},,,,我是promise来处理异步`) })
3.promise结合第一种方法
// 第三种
function getData(resolve,reject){
setTimeout(()=>{
let name = '我是第三种获取异步方法里面的数据';
resolve(name)
},1000)
}
var p1 = new Promise(getData)
p1.then(data=>{
console.log(`${data}我是第三种`)
})
4. async await 方法
async: 把函数变成异步函数,; await = async wait, 等待异步函数执行完成 (await一定要写在 async异步方法中)
// 第四种 async await
async function getdata2(){
return 'await,async,我是第四个方法'
}
async function test (){
let d = await getdata2()
console.log(d)
}
test()
5.async await 方法 和promise结合
// 第五种 async await 结合Promise
function getdata3(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
let name = '我是第五种方法';
resolve(name)
},1000)
})
}
async function test3(){
let aa = await getdata3()
console.log(aa)
}
test3()