參考資料:理解javaScript中的async/await,感謝原文做者的總結,本文在理解的基礎上作了一點小小的修改,主要爲了加深本身的知識點掌握java
學完了Promise,咱們知道能夠用then鏈來解決多層回調問題,可是這還不是最理想的操做,咱們須要調用不少個then鏈才能達到要求,那麼有沒有一種更簡便代碼量更少的方式達到then鏈相同的結果呢?asynv和await就很好地解決了這個問題,首先用async聲明一個異步函數,而後再用await等待異步結果,把之前then鏈的結果放到直接放在await,很是方便。segmentfault
那麼,async和await原理是什麼呢?爲何能夠用這樣的語法來優化then鏈呢?異步
async/await實際上是Promise的語法糖,它能實現的效果都能用then鏈來實現,這也和咱們以前提到的同樣,它是爲優化then鏈而開發出來的。從字面上來看,async是「異步」的簡寫,await譯爲等待,因此咱們很好理解async聲明function是異步的,await等待某個操做完成。固然語法上強制規定await只能出如今asnyc函數中,咱們先來看看async函數返回了什麼: async
async function testAsy(){ return 'hello world'; } let result = testAsy(); console.log(result)
這個async聲明的異步函數把return後面直接量經過Promise.resolve()返回Promise對象,因此若是這個最外層沒有用await調用的話,是能夠用原來then鏈的方式來調用的:函數
async function testAsy(){ return 'hello world' } let result = testAsy() console.log(result) result.then(v=>{ console.log(v) //hello world })
聯想一下Promise特色——異步無等待,因此當沒有await語句執行async函數,它就會當即執行,返回一個Promise對象,非阻塞,與普通的Promise對象函數一致。優化
重點就在await,它等待什麼呢?spa
按照語法說明,await等待的是一個Promise對象,或者是其餘值(也就是說能夠等待任何值),若是等待的是Promise對象,則返回Promise的處理結果;若是是其餘值,則返回該值自己。而且await會暫停當前async function的執行,等待Promise的處理完成。若Promise正常處理(fulfillded),其將回調的resolve函數參數做爲await表達式的值,繼續執行async function;若Promise處理異常(rejected),await表達式會把Promise異常緣由拋出;另外若是await操做符後面的表達式不是一個Promise對象,則返回該值自己。code
咱們來詳細說明一下async/await的做用。await操做符後面能夠是任意值,當是Promise對象的時候,會暫停async function執行。也就是說,必須得等待await後面的Promise處理完成才能繼續:對象
function testAsy(x){ return new Promise(resolve=>{setTimeout(() => { resolve(x); }, 3000) } ) } async function testAwt(){ let result = await testAsy('hello world'); console.log(result); // 3秒鐘以後出現hello world } testAwt();
await 表達式的運算結果取決於它等的東西。blog
若是它等到的不是一個 Promise 對象,那 await 表達式的運算結果就是它等到的東西。
若是它等到的是一個 Promise 對象,await 就忙起來了,它會阻塞後面的代碼,等着 Promise 對象 resolve,而後獲得 resolve 的值,做爲 await 表達式的運算結果。
咱們再把上面的代碼修改一下,好好體會「阻塞」這個詞
function testAsy(x){ return new Promise(resolve=>{setTimeout(() => { resolve(x); }, 3000) } ) } async function testAwt(){ let result = await testAsy('hello world'); console.log(result); // 3秒鐘以後出現hello world console.log('tangj') // 3秒鐘以後出現tangj } testAwt(); console.log('tangSir') //當即輸出tangSir
這就是 await 必須用在 async 函數中的緣由。async 函數調用不會形成阻塞,它內部全部的阻塞都被封裝在一個 Promise 對象中異步執行。await暫停當前async的執行,因此'tangSir''最早輸出,hello world'和‘tangj’是3秒鐘後同時出現的。
上面已經說明了 async 會將其後的函數(函數表達式或 Lambda)的返回值封裝成一個 Promise 對象,而 await 會等待這個 Promise 完成,並將其 resolve 的結果返回出來。
如今舉例,用 setTimeout模擬耗時的異步操做,先來看看不用 async/await 會怎麼寫
function takeLongTime() { return new Promise(resolve => { setTimeout(() => resolve("long_time_value"), 1000); }); } takeLongTime().then(v => { console.log("got", v); //一秒鐘後輸出got long_time_value });
若是改用 async/await 呢,會是這樣
function takeLongTime() { return new Promise(resolve => { setTimeout(() => resolve("long_time_value"), 1000); }); } async function test() { const v = await takeLongTime(); console.log(v); // 一秒鐘後輸出long_time_value } test();
tankLongTime()自己就是返回的 Promise 對象,因此加不加 async結果都同樣。
前面咱們說了,async和await是處理then鏈的語法糖,如今咱們來看看具體是怎麼實現的:
假設一個業務,分多個步驟完成,每一個步驟都是異步的,並且依賴於上一個步驟的結果。咱們仍然用setTimeout來模擬異步操做:
/** * 傳入參數 n,表示這個函數執行的時間(毫秒) * 執行的結果是 n + 200,這個值將用於下一步驟 */ function takeLongTime(n) { return new Promise(resolve => { setTimeout(() => resolve(n + 200), n); }); } function step1(n) { console.log(`step1 with ${n}`); return takeLongTime(n); } function step2(n) { console.log(`step2 with ${n}`); return takeLongTime(n); } function step3(n) { console.log(`step3 with ${n}`); return takeLongTime(n); }
如今用 Promise 方式來實現這三個步驟的處理。
function doIt(){ console.time('doIt'); let time1 = 300; step1(time1) .then((time2) => step2(time2)) .then((time3) => step3(time3)) .then((result) => { console.log(`result is ${result}`); console.timeEnd("doIt"); }) } doIt(); //執行結果爲: //step1 with 300 //step2 with 500 //step3 with 700 //result is 900 //doIt: 1510.2490234375ms
輸出結果 result
是 step3()
的參數 700 + 200
= 900
。doIt()
順序執行了三個步驟,一共用了 300 + 500 + 700 = 1500
毫秒,和 console.time()/console.timeEnd()
計算的結果一致。
若是用 async/await 來實現呢,會是這樣:
async function doIt() { console.time('doIt'); let time1 = 300; let time2 = await step1(time1);//將Promise對象resolve(n+200)的值賦給time2 let time3 = await step1(time2); let result = await step1(time3); console.log(`result is ${result}`); console.timeEnd('doIt'); } doIt(); //執行結果爲: //step1 with 300 //step2 with 500 //step3 with 700 //result is 900 //doIt: 1512.904296875ms
顯然咱們用async/await簡單多了。
await 命令後面的 Promise 對象,運行結果多是 rejected,因此最好把 await 命令放在 try...catch 代碼塊中。
async function myFunction() { try { await somethingThatReturnAPromise(); } catch (err){ console.log(err); } } //另外一種寫法 async function myFunction() { await somethingThatReturnAPromise().catch(function(err) { console.log(err); }) }