热点新闻
ES8(13)、await 和 async 的用法
2023-07-15 12:54  浏览:270  搜索引擎搜索“富博农业网”
温馨提示:为防找不到此信息,请务必收藏信息以备急用! 联系我时,请说明是在富博农业网看到的信息,谢谢。
展会发布 展会网站大全 报名观展合作 软文发布

async函数是使用async关键字声明的函数。 async函数是AsyncFunction构造函数的实例, 并且其中允许使用await关键字。asyncawait关键字让我们可以用一种更简洁的方式写出基于Promise的异步行为,而无需刻意地链式调用promise

1、先简单回顾一下Promise用法

function 摇色子(){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ let n=parseInt(Math.random()*6+1,10) //1~6的随机数 resolve(n) },1000) }) } 摇色子().then( x=>{ console.log("色子的点数是"+x); }, ()=>{ console.log("摇色子还能失败?"); }, )

2、上面采用链式.then调用promise,现在改用用async函数

function 摇色子(){ return new Promise((resolve,reject)=>{ setTimeout(()=>{ let n=parseInt(Math.random()*6+1,10) //1~6的随机数 resolve(n) },1000) }) } async function test(){ let n=await 摇色子() //await不能直接使用,必须要用async 声明的函数包裹才能使用,否则报错 console.log(n) } test()

3、改用了async...await,如果要打印出错误信息可以结合try...catch使用

function 猜大小(猜测){ return new Promise((resolve,reject)=>{ console.log("开始摇色子") setTimeout(()=>{ let n=parseInt(Math.random()*6+1,10) //1~6的随机数 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也有自己局限性,例如还是上面例子,如果我要同时进行两次猜色子游戏,

(1)、用链式.then写法:引用Promise.all这个API

Promise.all([猜大小('大'),猜大小('大')]) //引用Promise.all这个API,两者都成功才会执行 .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函数返回的值被解决,要么会通过一个从async函数中抛出的(或其中没有被捕获到的)异常被拒绝。

发布人:5f67****    IP:117.173.23.***     举报/删稿
展会推荐
让朕来说2句
评论
收藏
点赞
转发