一、含義
在早期,ES6 最初的異步處理方案引入 Promise 對象,后經(jīng)過升級成更好的異步編程解決方案:Generator 函數(shù)。
但是,Generator 函數(shù)是不能自動執(zhí)行的,返回的是一個遍歷器對象。需要借助 Thunk 函數(shù)或者 co 模塊實現(xiàn)自動流程管理。
為了使得異步操作變得更加合理,ES2017標準引入了 async 函數(shù)。相較于 Generator 函數(shù),async 函數(shù)有一下幾點優(yōu)勢:
1. 內(nèi)置執(zhí)行器
async 函數(shù)自帶執(zhí)行器,不需要像 Generator 函數(shù)需要 co 模塊實現(xiàn)自動流程管理。像調(diào)用普通函數(shù)一樣:asyncReadFile() ,只要一行,Generator 函數(shù)需要調(diào)用 next 方法或者借助 co 模塊才能得到最終結(jié)果。
2. 更好的語義性
async 和 await 比起星號和 yield,語義更清楚。async 表示函數(shù)里有異步操作,await 表示緊跟在后面的表達式需要等待結(jié)果。
3. 更廣的適用性
co 模塊約定,yield 命令后面只能是 Thunk 函數(shù) 或 Promise對象,而 async 函數(shù)的 await 命令后面,可以是 Promise 對象和原始類型的值(數(shù)值、字符串、布爾值,但這時等同于同步操作)。
4. 返回值是 Promise
async 函數(shù)的 返回值是 Promise對象,這比 Generator 函數(shù)的返回值是 Iterator 對象方便許多,可以用 then 方法指定下一步操作。
通俗講,async 函數(shù)是 Generator 函數(shù)的語法糖,是由多個異步操作包裝成的一個 Promise 對象,而 await 命令就是內(nèi)部 then 命令的語法糖。
二、用法
1、多種使用形式
// 函數(shù)聲明
async function foo() {};
// 函數(shù)表達式
const = foo = async function() {};
// 對象的方法
let obj = { async foo() {} };
obj.foo().then(...);
// calss 的方法
class Storage {
constructor() {
this.cachePromise = caches.open('yuan');
}
async getYuan(name) {
const cache = await this.cachePromise;
return cache.match(`/yuan/${ name } .png`);
}
}
const storage = new Storage();
storage.getYuan('monkey').then(...);
// 箭頭函數(shù)
const foo = async () => {};
2、返回 Promise 對象
async 函數(shù)內(nèi)部 return 語句返回的值,會成為 then 方法回調(diào)函數(shù)的參數(shù)
async function f() {
return "hello world";
}
f().then(v => console.log(v)); // hello world
3、Promise 對象的狀態(tài)變化
只有 async 函數(shù)內(nèi)部的 await 命令執(zhí)行完,才會執(zhí)行 then 方法指定的回調(diào)函數(shù):
async function getTitle(url) {
let response = await fetch(url);
let html = response.text(0;
return html..match(/<title>([\s\S]+<\title>/i)[1];
}
getTitle("http://www.itdecent.cn/writer#/notebooks/15137721/notes/24616981/preview").then(...);
上述代碼中 getTitle 函數(shù)內(nèi)部的3個操作:抓取網(wǎng)頁、取出文本。匹配頁面標題。只有執(zhí)行完這三個操作,才能執(zhí)行 then 方法里的操作。
4、await 命令
await 命令后面是一個 Promise 對象,如果不是,會自動被轉(zhuǎn)為一個 resolve 的 Promise 對象:
async function f() {
return await 'yuan';
}
f().then(v => console.log(v)); // yuan
await 命令后沒的 Promise 對象如果變?yōu)?reject 狀態(tài),則 reject 的參數(shù)會被 catch 方法的回調(diào)函數(shù)接收到:
async function foo() {
await Promise.reject('報錯了');
}
foo()
.then(v => console.log(v))
.catch( e => console.log(e))
// 瀏覽器拋出錯誤
只要有一個 await 命令后面的 Promise 對象變?yōu)?reject,那么整個 async 函數(shù)都會中斷。
三、使用注意點
1、await 命令后面的 Promise 對象運行的結(jié)果可能是 reject 的狀態(tài),所以最好把 await 命令放在 try...catch 代碼塊里,或者在
await 命令后加一個 catch 方法:
// await 命令寫在 try...catch
async function f() {
try {
await somePromise();
}
catch(err) {
console.log(err);
}
}
// 在 await 后加 catch
async function f() {
await somePromise()
.catch (function (err) {
console.log(err)
});
}
2、多個 await 名利后面的異步操作如果不存在繼發(fā)關(guān)系,最好讓他們同時出發(fā)
let foo = await getFoo();
let bar = await getBar();
3、await 命令只能用在 async 函數(shù)之中,如果用在普通函數(shù)中會報錯
4、多個請求并發(fā)執(zhí)行,可以使用 Promise.all 方法:
async function dbFunc(db) {
let docs = [{}, {}, {}];
let promises = doc.map((doc) = > db.post(doc));
let results = await Promise.all(promises);
console.log(results);
}
四、異步應(yīng)用對比:Promise、Generator、async
以 setTimeout 來模擬異步操作:
function foo (obj) {
return new Promise((resolve, reject) => {
window.setTimeout(() => {
let data = {
height: 180
}
data = Object.assign({}, obj, data)
resolve(data)
}, 1000)
})
}
function bar (obj) {
return new Promise((resolve, reject) => {
window.setTimeout(() => {
let data = {
talk () {
console.log(this.name, this.height);
}
}
data = Object.assign({}, obj, data)
resolve(data)
}, 1500)
})
}
兩個函數(shù)都返回了 Promise 對象,使用 Object.assign() 方法合并傳遞過來的參數(shù)。
Promise 實現(xiàn)異步:
function main () {
return new Promise((resolve, reject) => {
const data = {
name: 'keith'
}
resolve(data)
})
}
main().then(data => {
foo(data).then(res => {
bar(res).then(data => {
return data.talk() // keith 180
})
})
})
此方法的缺點:語義不好,不夠直觀,使用多個 then 方法,有可能出現(xiàn)回調(diào)地獄。
Generator 函數(shù)實現(xiàn)異步:
function *gen () {
const data = {
name: 'keith'
}
const fooData = yield foo(data)
const barData = yield bar(fooData)
return barData.talk()
}
function run (gen) {
const g = gen()
const next = data => {
let result = g.next(data)
if (result.done) return result.value
result.value.then(data => {
next(data)
})
}
next()
}
run(gen)
Generator 函數(shù)相較于 Promise 實現(xiàn)異步操作,優(yōu)點在于:異步過程同步化,避免回調(diào)地獄的出現(xiàn)。缺點在于:需要借助run 函數(shù)或者 co 模塊實現(xiàn)流程的自動管理。
async 函數(shù)實現(xiàn)異步:
async function main () {
const data = {
name: 'keith'
}
const fooData = await foo(data)
const barData = await bar(fooData)
return barData
}
main().then(data => {
data.talk()
})
async 函數(shù)優(yōu)點在于:實現(xiàn)了執(zhí)行器的內(nèi)置,代碼量減少,且異步過程同步化,語義化更強。
五、應(yīng)用實例
1、從豆瓣API上獲取數(shù)據(jù):
var fetchDoubanApi = function() {
return new Promise((resolve, reject) = >{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (xhr.status >= 200 && xhr.status < 300) {
var response;
try {
response = JSON.parse(xhr.responseText);
} catch(e) {
reject(e);
}
if (response) {
resolve(response, xhr.status, xhr);
}
} else {
reject(xhr);
}
}
};
xhr.open('GET', 'https://api.douban.com/v2/user/aisk', true);
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.send(data);
});
};
(async function() {
try {
let result = await fetchDoubanApi();
console.log(result);
} catch(e) {
console.log(e);
}
})();
2、根據(jù)電影名稱,下載對應(yīng)的海報
import fs from 'fs';
import path from 'path';
import request from 'request';
var movieDir = __dirname + '/movies',
exts = ['.mkv', '.avi', '.mp4', '.rm', '.rmvb', '.wmv'];
// 讀取文件列表
var readFiles = function() {
return new Promise(function(resolve, reject) {
fs.readdir(movieDir,
function(err, files) {
resolve(files.filter((v) = >exts.includes(path.parse(v).ext)));
});
});
};
// 獲取海報
var getPoster = function(movieName) {
let url = `https: //api.douban.com/v2/movie/search?q=${encodeURI(movieName)}`;
return new Promise(function(resolve, reject) {
request({
url: url,
json: true
},
function(error, response, body) {
if (error) return reject(error);
resolve(body.subjects[0].images.large);
})
});
};
// 保存海報
var savePoster = function(movieName, url) {
request.get(url).pipe(fs.createWriteStream(path.join(movieDir, movieName + '.jpg')));
};
(async() = >{
let files = await readFiles();
// await只能使用在原生語法
for (var file of files) {
let name = path.parse(file).name;
console.log(`正在獲取【$ {
name
}】的海報`);
savePoster(name, await getPoster(name));
}
console.log('=== 獲取海報完成 ===');
})();
六、結(jié)語
本章,我們需要對比 Promise 和 Generator 異步操作的優(yōu)勢了解 async 函數(shù)的由來,掌握 async 函數(shù)的用法及其注意事項,再結(jié)合相應(yīng)的實例深入了解 async 函數(shù)的實現(xiàn)原理。下一章,我們來了解 ES6 另一個語法糖: class,盡情期待吧!
章節(jié)目錄
1、ES6中啥是塊級作用域?運用在哪些地方?
2、ES6中使用解構(gòu)賦值能帶給我們什么?
3、ES6字符串擴展增加了哪些?
4、ES6對正則做了哪些擴展?
5、ES6數(shù)值多了哪些擴展?
6、ES6函數(shù)擴展(箭頭函數(shù))
7、ES6 數(shù)組給我們帶來哪些操作便利?
8、ES6 對象擴展
9、Symbol 數(shù)據(jù)類型在 ES6 中起什么作用?
10、Map 和 Set 兩數(shù)據(jù)結(jié)構(gòu)在ES6的作用
11、ES6 中的Proxy 和 Reflect 到底是什么鬼?
12、從 Promise 開始踏入異步操作之旅
13、ES6 迭代器(Iterator)和 for...of循環(huán)使用方法
14、ES6 異步進階第二步:Generator 函數(shù)
15、JavaScript 異步操作進階第三步:async 函數(shù)
16、ES6 構(gòu)造函數(shù)語法糖:class 類