ES2017 標準引入了 async 函數,使得異步操做變得更加方便。javascript
在異步處理上,async 函數就是 Generator 函數的語法糖。java
舉個例子:node
// 使用 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 時:git
// 使用 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 函數和自動執行器,包裝在一個函數裏。es6
async function fn(args) {
// ...
}
// 等同於
function fn(args) {
return spawn(function* () {
// ...
});
}
複製代碼
spawn 函數指的是自動執行器,就好比說 co。github
再加上 async 函數返回一個 Promise 對象,你也能夠理解爲 async 函數是基於 Promise 和 Generator 的一層封裝。json
嚴謹的說,async 是一種語法,Promise 是一個內置對象,二者並不具有可比性,更況且 async 函數也返回一個 Promise 對象……segmentfault
這裏主要是展現一些場景,使用 async 會比使用 Promise 更優雅的處理異步流程。api
/** * 示例一 */
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)
};
複製代碼
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 就能夠捕獲同步和異步的錯誤。
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 () => {
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);
}
}
複製代碼
儘管咱們可使用 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');
}
}
複製代碼
Generator 原本是用做生成器,使用 Generator 處理異步請求只是一個比較 hack 的用法,在異步方面,async 能夠取代 Generator,可是 async 和 Generator 兩個語法自己是用來解決不一樣的問題的。
async 函數返回一個 Promise 對象
面對複雜的異步流程,Promise 提供的 all 和 race 會更加好用
Promise 自己是一個對象,因此能夠在代碼中任意傳遞
async 的支持率還很低,即便有 Babel,編譯後也要增長 1000 行左右。
ES6 系列目錄地址:github.com/mqyqingfeng…
ES6 系列預計寫二十篇左右,旨在加深 ES6 部分知識點的理解,重點講解塊級做用域、標籤模板、箭頭函數、Symbol、Set、Map 以及 Promise 的模擬實現、模塊加載方案、異步處理等內容。
若是有錯誤或者不嚴謹的地方,請務必給予指正,十分感謝。若是喜歡或者有所啓發,歡迎 star,對做者也是一種鼓勵。