特点
Async Await 为 Promise 延伸出的特性,是 Promise 的语法糖函式本体是属于非同步,但内部以 “同步的方式运行非同步” 程式码更加简洁处理非同步事件,提高程式码可读性使用 try...catch 管理流程,将非同步事件置入于 try 流程内,当遇到错误时则在 catch 区块内接取错误讯息
各情况範例
与 Promise 搭配执行
let event = (num) => Math.floor(Math.random() *num)>2 ? true : falselet timer = (num) => Math.floor(Math.random() * num)*1000let condition = function(something,timer,num) { return new Promise((resolve,reject)=>{ setTimeout(function(){ if(something) { resolve('第'+ num +".成功了花了"+timer+'秒'); } else { reject('第'+ num +'次失败QQ'); } },timer) })}//----------------------------只有一个非同步事件的情况----------------------------------async function example() { try{ const res1 = await condition(event(5),timer(5),1) console.log('event1:',res1) } catch(err){ console.log('失败:',err) }}//---------若是两个事件以上,只要其中一个出现错误,即进入catch的阶段,并不在继续往下执行-----------async function example() { try{ const res1 = await condition(event(5),timer(5),1) console.log('event1:',res1) const res2 = await condition(event(5),timer(5),2) console.log('event2:',res2) const res3 = await condition(event(5),timer(5),3) console.log('event3:',res3) } catch(err){ console.log('失败:',err) }}/*----------与 Promise.all() 搭配,在全部完成后才进行下一步,若事件都成功,则印出阵列回复,若其中rejected,.catch立即回传第一个完成的失败回复-----------*/ //-----与 Promise.race() 搭配,其中一事件先完成(不论成功与否),即进入对应的try...catch----------async function example() { try{ const res = await Promise.all([condition(event(5),timer(5),1),condition(event(5),timer(5),2),condition(event(5),timer(5),3),condition(event(5),timer(5),4)]) console.log(res) } catch(err){ console.log('失败:',err) }}//----------------------------------------------------------------------------------example()