async函數的特色:promise
例:async
router.get('/testAsync',async (ctx)=>{ global.console.log('start',new Date().getTime()); const a = await new Promise((resolve,reject)=>{ setTimeout(()=>{ global.console.log('async a',new Date().getTime()); resolve('a') },1000) }); const b = await 123 const c = await new Promise((resolve,reject)=>{ setTimeout(()=>{ global.console.log('async a',new Date().getTime()); resolve('c') },2000) }) ctx.body = { a,b,c }; })
看看代碼的執行過程,它裏面遇到了await, await 表示等待,代碼就暫停到這裏,再也不向下執行了,它等待後面的promise對象執行完畢,而後拿到promise resolve 的值並進行返回,返回值拿到以後,它繼續向下執行。具體到 咱們的代碼, 遇到await 以後,代碼就暫停執行了, 等待後面promise執行完畢,暫停結束,代碼繼續執行。函數
怎麼處理異常,若是請求發生異常,怎麼處理? this
它用的是try/catch 來捕獲異常,把await 放到 try 中進行執行,若有異常,就使用catch 進行處理。spa
async getFaceResult () { try { let location = await this.getLocation(this.phoneNum); if (location.data.success) { let province = location.data.obj.province; let city = location.data.obj.city; let result = await this.getFaceList(province, city); if (result.data.success) { this.faceList = result.data.obj; } } } catch(err) { console.log(err); } }