async函數(shù)是使用async
關(guān)鍵字聲明的函數(shù)。 async函數(shù)是AsyncFunction
構(gòu)造函數(shù)的實例禁舷, 并且其中允許使用await
關(guān)鍵字彪杉。async
和await
關(guān)鍵字讓我們可以用一種更簡潔的方式寫出基于Promise
的異步行為,而無需刻意地鏈?zhǔn)秸{(diào)用promise
牵咙。
1派近、先簡單回顧一下Promise用法
function 搖色子(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
let n=parseInt(Math.random()*6+1,10) //1~6的隨機數(shù)
resolve(n)
},1000)
})
}
搖色子().then(
x=>{
console.log("色子的點數(shù)是"+x);
},
()=>{
console.log("搖色子還能失敗洁桌?");
},
)
2渴丸、上面采用鏈?zhǔn)?code>.then調(diào)用promise
,現(xiàn)在改用用async函數(shù)
function 搖色子(){
return new Promise((resolve,reject)=>{
setTimeout(()=>{
let n=parseInt(Math.random()*6+1,10) //1~6的隨機數(shù)
resolve(n)
},1000)
})
}
async function test(){
let n=await 搖色子() //await不能直接使用另凌,必須要用async 聲明的函數(shù)包裹才能使用谱轨,否則報錯
console.log(n)
}
test()
3、改用了async...await
吠谢,如果要打印出錯誤信息可以結(jié)合try...catch
使用
function 猜大小(猜測){
return new Promise((resolve,reject)=>{
console.log("開始搖色子")
setTimeout(()=>{
let n=parseInt(Math.random()*6+1,10) //1~6的隨機數(shù)
if(n>3){
if(猜測==="大"){
resolve(n);
}else{
console.log('error')
reject(n)
}
}else{
if(猜測==="小"){
resolve(n);
}else{
console.log('error')
reject(n)
}
}
resolve(n)
},1000)
})
}
async function test(){
try{
let n=await 猜大小("大")
console.log("中獎了"+n)
}catch(error){
console.log("輸光了"+error)
}
}
test()
4土童、但是async...await
也有自己局限性,例如還是上面例子工坊,如果我要同時進(jìn)行兩次猜色子游戲献汗,
(1)、用鏈?zhǔn)?code>.then寫法:引用Promise.all這個API
Promise.all([猜大小('大'),猜大小('大')]) //引用Promise.all這個API王污,兩者都成功才會執(zhí)行
.then((x)=>{console.log(x)},(y)=>{console.log(y)})
(1)罢吃、用async...await
寫法:還是引用Promise.all這個API
async function test(){
try{
let n=await Promise.all([猜大小('大'),猜大小('大')])
console.log("中獎了"+n)
}catch(error){
console.log("輸光了"+error)
}
}
test()
4、使用async...await
返回值依舊是一個Promise
昭齐,這個promise要么會通過一個由async函數(shù)返回的值被解決尿招,要么會通過一個從async函數(shù)中拋出的(或其中沒有被捕獲到的)異常被拒絕。