在項目中有些邏輯或者請求依賴另外一個異步請求,你們經常使用的方法是回調函數。如今有個高大上的解決方案:await async 。ios
async 是「異步」的簡寫,而 await 能夠認爲是 async wait 的簡寫。因此應該很好理解 async 用於申明一個 function 是異步的,而 await 用於等待一個異步方法執行完成。而且await 只能出如今 async 函數中,不然會報錯。axios
async做用:異步
當調用一個 async
函數時,會返回一個 Promise
對象。當這個 async
函數返回一個值時,Promise
的 resolve 方法會負責傳遞這個值;當 async
函數拋出異常時,Promise
的 reject 方法也會傳遞這個異常值。async
async
函數中可能會有 await
表達式,這會使 async
函數暫停執行,等待 Promise
的結果出來,而後恢復async
函數的執行並返回解析值(resolved)。函數
await做用:url
await 表達式會暫停當前 async function
的執行,等待 Promise 處理完成。若 Promise 正常處理(fulfilled),其回調的resolve函數參數做爲 await 表達式的值,繼續執行 async function
。spa
若 Promise 處理異常(rejected),await 表達式會把 Promise 的異常緣由拋出。另外,若是 await 操做符後的表達式的值不是一個 Promise,則返回該值自己。code
來個栗子:對象
function resolveAfter2Seconds() { return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } async function asyncCall() { console.log('calling1'); var result = await resolveAfter2Seconds(); console.log(result); console.log('calling2'); // expected output: 'calling1','resolved','calling2' } asyncCall();
結合實際:blog
function getData() { return axios.get('/url') } async function asyncCall() { var {data} = await getData(); console.log(data) } asyncCall();
須要注意的:
function getData1() { console.log(new Date()) return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } function getData2() { console.log(new Date()) return new Promise(resolve => { setTimeout(() => { resolve('resolved2'); }, 2000); }); } async function asyncCall() { var data1 = await getData1(); var data2 = await getData2(); console.log(data1) console.log(data2) } asyncCall();
結果:
Mon Apr 29 2019 14:42:14 GMT+0800 (中國標準時間)
Mon Apr 29 2019 14:42:16 GMT+0800 (中國標準時間)
resolved
resolved2
能夠看出 getData2 在 getData1執行完後才執行,若是getData2不依賴getData1的返回值,會形成時間的浪費。能夠改爲下面這樣:
function getData1() { console.log(new Date()) return new Promise(resolve => { setTimeout(() => { resolve('resolved'); }, 2000); }); } function getData2() { console.log(new Date()) return new Promise(resolve => { setTimeout(() => { resolve('resolved2'); }, 2000); }); } async function asyncCall() { var data1 = getData1(); var data2 = getData2(); data1 = await data1 data2 = await data2 console.log(data1) console.log(data2) } asyncCall();
結果:
Mon Apr 29 2019 14:51:52 GMT+0800 (中國標準時間)
Mon Apr 29 2019 14:51:52 GMT+0800 (中國標準時間)
resolvedresolved2