前面我们介绍的是promise对象,这里我们介绍一下async...await异步函数,创建函数时候使用async关键词表示这是一个异步函数,await必须和async搭配使用
async的使用
function wait1(){
return p = new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log("1S later")
resolve()
},1000)
})
}
function wait2(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log("2S later")
resolve()
},2000)
})
}
async function test() {
console.log("开始执行")
await wait1()
await wait2()
await new Promise((resolve,reject)=>{
setTimeout(()=>{
console.log("馬上執行成功!等待初始化...")
resolve()
},4000)
})
console.log("执行完毕")
console.log('Over!')
}
test()
当我们执行某件事需要依托前面为铺垫,我们可以很容易使用这个async函数,await的等待必须是一个promise对象,否则无效,它比之前的.then更加优雅易懂!这个async...await是ES7的新特性!