ES6 系列之我們來聊聊 Async
ES2017 標準引入了 async 函式,使得非同步操作變得更加方便。
在非同步處理上,async 函式就是 Generator 函式的語法糖。
舉個例子:
// 使用 generator var fetch = require('node-fetch'); var co = require('co'); function* gen() { var r1 = yield fetch('https://api.github.com/users/github'); var json1 = yield r1.json(); console.log(json1.bio); } co(gen); 複製程式碼
當你使用 async 時:
// 使用 async var fetch = require('node-fetch'); var fetchData = async function () { var r1 = await fetch('https://api.github.com/users/github'); var json1 = await r1.json(); console.log(json1.bio); }; fetchData(); 複製程式碼
其實 async 函式的實現原理,就是將 Generator 函式和自動執行器,包裝在一個函式裡。
async function fn(args) { // ... } // 等同於 function fn(args) { return spawn(function* () { // ... }); } 複製程式碼
spawn 函式指的是自動執行器,就比如說 co。
再加上 async 函式返回一個 Promise 物件,你也可以理解為 async 函式是基於 Promise 和 Generator 的一層封裝。
async 與 Promise
嚴謹的說,async 是一種語法,Promise 是一個內建物件,兩者並不具備可比性,更何況 async 函式也返回一個 Promise 物件……
這裡主要是展示一些場景,使用 async 會比使用 Promise 更優雅的處理非同步流程。
1. 程式碼更加簡潔
/** * 示例一 */ function fetch() { return ( fetchData() .then(() => { return "done" }); ) } async function fetch() { await fetchData() return "done" }; 複製程式碼
/** * 示例二 */ function fetch() { return fetchData() .then(data => { if (data.moreData) { return fetchAnotherData(data) .then(moreData => { return moreData }) } else { return data } }); } async function fetch() { const data = await fetchData() if (data.moreData) { const moreData = await fetchAnotherData(data); return moreData } else { return data } }; 複製程式碼
/** * 示例三 */ function fetch() { return ( fetchData() .then(value1 => { return fetchMoreData(value1) }) .then(value2 => { return fetchMoreData2(value2) }) ) } async function fetch() { const value1 = await fetchData() const value2 = await fetchMoreData(value1) return fetchMoreData2(value2) }; 複製程式碼
2. 錯誤處理
function fetch() { try { fetchData() .then(result => { const data = JSON.parse(result) }) .catch((err) => { console.log(err) }) } catch (err) { console.log(err) } } 複製程式碼
在這段程式碼中,try/catch 能捕獲 fetchData() 中的一些 Promise 構造錯誤,但是不能捕獲 JSON.parse 丟擲的異常,如果要處理 JSON.parse 丟擲的異常,需要新增 catch 函式重複一遍異常處理的邏輯。
在實際專案中,錯誤處理邏輯可能會很複雜,這會導致冗餘的程式碼。
async function fetch() { try { const data = JSON.parse(await fetchData()) } catch (err) { console.log(err) } }; 複製程式碼
async/await 的出現使得 try/catch 就可以捕獲同步和非同步的錯誤。
3. 除錯
const fetchData = () => new Promise((resolve) => setTimeout(resolve, 1000, 1)) const fetchMoreData = (value) => new Promise((resolve) => setTimeout(resolve, 1000, value + 1)) const fetchMoreData2 = (value) => new Promise((resolve) => setTimeout(resolve, 1000, value + 2)) function fetch() { return ( fetchData() .then((value1) => { console.log(value1) return fetchMoreData(value1) }) .then(value2 => { return fetchMoreData2(value2) }) ) } const res = fetch(); console.log(res); 複製程式碼

因為 then 中的程式碼是非同步執行,所以當你打斷點的時候,程式碼不會順序執行,尤其當你使用 step over 的時候,then 函式會直接進入下一個 then 函式。
const fetchData = () => new Promise((resolve) => setTimeout(resolve, 1000, 1)) const fetchMoreData = () => new Promise((resolve) => setTimeout(resolve, 1000, 2)) const fetchMoreData2 = () => new Promise((resolve) => setTimeout(resolve, 1000, 3)) async function fetch() { const value1 = await fetchData() const value2 = await fetchMoreData(value1) return fetchMoreData2(value2) }; const res = fetch(); console.log(res); 複製程式碼

而使用 async 的時候,則可以像除錯同步程式碼一樣除錯。
async 地獄
async 地獄主要是指開發者貪圖語法上的簡潔而讓原本可以並行執行的內容變成了順序執行,從而影響了效能,但用地獄形容有點誇張了點……
例子一
舉個例子:
(async () => { const getList = await getList(); const getAnotherList = await getAnotherList(); })(); 複製程式碼
getList() 和 getAnotherList() 其實並沒有依賴關係,但是現在的這種寫法,雖然簡潔,卻導致了 getAnotherList() 只能在 getList() 返回後才會執行,從而導致了多一倍的請求時間。
為了解決這個問題,我們可以改成這樣:
(async () => { const listPromise = getList(); const anotherListPromise = getAnotherList(); await listPromise; await anotherListPromise; })(); 複製程式碼
也可以使用 Promise.all():
(async () => { Promise.all([getList(), getAnotherList()]).then(...); })(); 複製程式碼
例子二
當然上面這個例子比較簡單,我們再來擴充一下:
(async () => { const listPromise = await getList(); const anotherListPromise = await getAnotherList(); // do something await submit(listData); await submit(anotherListData); })(); 複製程式碼
因為 await 的特性,整個例子有明顯的先後順序,然而 getList() 和 getAnotherList() 其實並無依賴,submit(listData) 和 submit(anotherListData) 也沒有依賴關係,那麼對於這種例子,我們該怎麼改寫呢?
基本分為三個步驟:
1. 找出依賴關係
在這裡,submit(listData) 需要在 getList() 之後,submit(anotherListData) 需要在 anotherListPromise() 之後。
2. 將互相依賴的語句包裹在 async 函式中
async function handleList() { const listPromise = await getList(); // ... await submit(listData); } async function handleAnotherList() { const anotherListPromise = await getAnotherList() // ... await submit(anotherListData) } 複製程式碼
3.併發執行 async 函式
async function handleList() { const listPromise = await getList(); // ... await submit(listData); } async function handleAnotherList() { const anotherListPromise = await getAnotherList() // ... await submit(anotherListData) } // 方法一 (async () => { const handleListPromise = handleList() const handleAnotherListPromise = handleAnotherList() await handleListPromise await handleAnotherListPromise })() // 方法二 (async () => { Promise.all([handleList(), handleAnotherList()]).then() })() 複製程式碼
繼發與併發
問題:給定一個 URL 陣列,如何實現介面的繼發和併發?
async 繼發實現:
// 繼發一 async function loadData() { var res1 = await fetch(url1); var res2 = await fetch(url2); var res3 = await fetch(url3); return "whew all done"; } 複製程式碼
// 繼發二 async function loadData(urls) { for (const url of urls) { const response = await fetch(url); console.log(await response.text()); } } 複製程式碼
async 併發實現:
// 併發一 async function loadData() { var res = await Promise.all([fetch(url1), fetch(url2), fetch(url3)]); return "whew all done"; } 複製程式碼
// 併發二 async function loadData(urls) { // 併發讀取 url const textPromises = urls.map(async url => { const response = await fetch(url); return response.text(); }); // 按次序輸出 for (const textPromise of textPromises) { console.log(await textPromise); } } 複製程式碼
async 錯誤捕獲
儘管我們可以使用 try catch 捕獲錯誤,但是當我們需要捕獲多個錯誤並做不同的處理時,很快 try catch 就會導致程式碼雜亂,就比如:
async function asyncTask(cb) { try { const user = await UserModel.findById(1); if(!user) return cb('No user found'); } catch(e) { return cb('Unexpected error occurred'); } try { const savedTask = await TaskModel({userId: user.id, name: 'Demo Task'}); } catch(e) { return cb('Error occurred while saving task'); } if(user.notificationsEnabled) { try { await NotificationService.sendNotification(user.id, 'Task Created'); } catch(e) { return cb('Error while sending notification'); } } if(savedTask.assignedUser.id !== user.id) { try { await NotificationService.sendNotification(savedTask.assignedUser.id, 'Task was created for you'); } catch(e) { return cb('Error while sending notification'); } } cb(null, savedTask); } 複製程式碼
為了簡化這種錯誤的捕獲,我們可以給 await 後的 promise 物件新增 catch 函式,為此我們需要寫一個 helper:
// to.js export default function to(promise) { return promise.then(data => { return [null, data]; }) .catch(err => [err]); } 複製程式碼
整個錯誤捕獲的程式碼可以簡化為:
import to from './to.js'; async function asyncTask() { let err, user, savedTask; [err, user] = await to(UserModel.findById(1)); if(!user) throw new CustomerError('No user found'); [err, savedTask] = await to(TaskModel({userId: user.id, name: 'Demo Task'})); if(err) throw new CustomError('Error occurred while saving task'); if(user.notificationsEnabled) { const [err] = await to(NotificationService.sendNotification(user.id, 'Task Created')); if (err) console.error('Just log the error and continue flow'); } } 複製程式碼
async 的一些討論
async 會取代 Generator 嗎?
Generator 本來是用作生成器,使用 Generator 處理非同步請求只是一個比較 hack 的用法,在非同步方面,async 可以取代 Generator,但是 async 和 Generator 兩個語法本身是用來解決不同的問題的。
async 會取代 Promise 嗎?
-
async 函式返回一個 Promise 物件
-
面對複雜的非同步流程,Promise 提供的 all 和 race 會更加好用
-
Promise 本身是一個物件,所以可以在程式碼中任意傳遞
-
async 的支援率還很低,即使有 Babel,編譯後也要增加 1000 行左右。
參考
- ofollow,noindex">[譯] 6 個 Async/Await 優於 Promise 的方面
- [譯] 如何逃離 async/await 地獄
- 精讀《async/await 是把雙刃劍》
- ECMAScript 6 入門
- How to write async await without try-catch blocks in Javascript
ES6 系列
ES6 系列目錄地址: github.com/mqyqingfeng…
ES6 系列預計寫二十篇左右,旨在加深 ES6 部分知識點的理解,重點講解塊級作用域、標籤模板、箭頭函式、Symbol、Set、Map 以及 Promise 的模擬實現、模組載入方案、非同步處理等內容。
如果有錯誤或者不嚴謹的地方,請務必給予指正,十分感謝。如果喜歡或者有所啟發,歡迎 star,對作者也是一種鼓勵。