ES6学习笔记(十六)async函数
1.含義
ES2017 標(biāo)準(zhǔn)引入了 async 函數(shù),使得異步操作變得更加方便。
async 函數(shù)是什么?一句話,它就是 Generator 函數(shù)的語法糖,號稱異步的終極解決方案。
前文有一個(gè) Generator 函數(shù),依次讀取兩個(gè)文件。
1 const fs = require('fs'); 2 3 const readFile = function (fileName) { 4 return new Promise(function (resolve, reject) { 5 fs.readFile(fileName, function(error, data) { 6 if (error) return reject(error); 7 resolve(data); 8 }); 9 }); 10 }; 11 12 const gen = function* () { 13 const f1 = yield readFile('/etc/fstab'); 14 const f2 = yield readFile('/etc/shells'); 15 console.log(f1.toString()); 16 console.log(f2.toString()); 17 };上面代碼的函數(shù)gen可以寫成async函數(shù),就是下面這樣。
const asyncReadFile = async function () {const f1 = await readFile('/etc/fstab');const f2 = await readFile('/etc/shells');console.log(f1.toString());console.log(f2.toString()); };一比較就會發(fā)現(xiàn),async函數(shù)就是將 Generator 函數(shù)的星號(*)替換成async,將yield替換成await,僅此而已。
async函數(shù)對 Generator 函數(shù)的改進(jìn),體現(xiàn)在以下四點(diǎn)。
(1)內(nèi)置執(zhí)行器。
Generator 函數(shù)的執(zhí)行必須靠執(zhí)行器,所以才有了co模塊,而async函數(shù)自帶執(zhí)行器。也就是說,async函數(shù)的執(zhí)行,與普通函數(shù)一模一樣,只要一行。
asyncReadFile();上面的代碼調(diào)用了asyncReadFile函數(shù),然后它就會自動執(zhí)行,輸出最后結(jié)果。這完全不像 Generator 函數(shù),需要調(diào)用next方法,或者用co模塊,才能真正執(zhí)行,得到最后結(jié)果。
(2)更好的語義。
async和await,比起星號和yield,語義更清楚了。async表示函數(shù)里有異步操作,await表示緊跟在后面的表達(dá)式需要等待結(jié)果。
(3)更廣的適用性。
co模塊約定,yield命令后面只能是 Thunk 函數(shù)或 Promise 對象,而async函數(shù)的await命令后面,可以是 Promise 對象和原始類型的值(數(shù)值、字符串和布爾值,但這時(shí)會自動轉(zhuǎn)成立即 resolved 的 Promise 對象)。
(4)返回值是 Promise。
async函數(shù)的返回值是 Promise 對象,這比 Generator 函數(shù)的返回值是 Iterator 對象方便多了。你可以用then方法指定下一步的操作。
進(jìn)一步說,async函數(shù)完全可以看作多個(gè)異步操作,包裝成的一個(gè) Promise 對象,而await命令就是內(nèi)部then命令的語法糖。
2.基本用法
async函數(shù)返回一個(gè) Promise 對象,可以使用then方法添加回調(diào)函數(shù)。當(dāng)函數(shù)執(zhí)行的時(shí)候,一旦遇到await就會先返回,等到異步操作完成,再接著執(zhí)行函數(shù)體內(nèi)后面的語句。
async function getStockPriceByName(name) {const symbol = await getStockSymbol(name);const stockPrice = await getStockPrice(symbol);return stockPrice; }getStockPriceByName('goog').then(function (result) {console.log(result); });上面代碼是一個(gè)獲取股票報(bào)價(jià)的函數(shù),函數(shù)前面的async關(guān)鍵字,表明該函數(shù)內(nèi)部有異步操作。調(diào)用該函數(shù)時(shí),會立即返回一個(gè)Promise對象。
1 function timeout(ms) { 2 return new Promise((resolve) => { 3 setTimeout(resolve, ms); 4 }); 5 } 6 7 async function asyncPrint(value, ms) { 8 await timeout(ms); 9 console.log(value); 10 } 11 12 asyncPrint('hello world', 50);上面代碼指定 50 毫秒以后,輸出hello world。
由于async函數(shù)返回的是 Promise 對象,可以作為await命令的參數(shù)。所以,上面的例子也可以寫成下面的形式。
1 async function timeout(ms) { 2 await new Promise((resolve) => { 3 setTimeout(resolve, ms); 4 }); 5 } 6 7 async function asyncPrint(value, ms) { 8 await timeout(ms); 9 console.log(value); 10 } 11 12 asyncPrint('hello world', 50);async 函數(shù)有多種使用形式。
1 // 函數(shù)聲明 2 async function foo() {} 3 4 // 函數(shù)表達(dá)式 5 const foo = async function () {}; 6 7 // 對象的方法 8 let obj = { async foo() {} }; 9 obj.foo().then(...) 10 11 // Class 的方法 12 class Storage { 13 constructor() { 14 this.cachePromise = caches.open('avatars'); 15 } 16 17 async getAvatar(name) { 18 const cache = await this.cachePromise; 19 return cache.match(`/avatars/${name}.jpg`); 20 } 21 } 22 23 const storage = new Storage(); 24 storage.getAvatar('jake').then(…); 25 26 // 箭頭函數(shù) 27 const foo = async () => {};3.語法
async函數(shù)的語法規(guī)則總體上比較簡單,難點(diǎn)是錯(cuò)誤處理機(jī)制。
返回 Promise 對象?
async函數(shù)返回一個(gè) 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"上面代碼中,函數(shù)f內(nèi)部return命令返回的值,會被then方法回調(diào)函數(shù)接收到。
async函數(shù)內(nèi)部拋出錯(cuò)誤,會導(dǎo)致返回的 Promise 對象變?yōu)?span style="color:#ff0000;">reject狀態(tài)。拋出的錯(cuò)誤對象會被catch方法回調(diào)函數(shù)接收到。
async function f() {throw new Error('出錯(cuò)了'); }f().then(v => console.log(v),e => console.log(e) ) // Error: 出錯(cuò)了Promise 對象的狀態(tài)變化
async函數(shù)返回的 Promise 對象,必須等到內(nèi)部所有await命令后面的 Promise 對象執(zhí)行完,才會發(fā)生狀態(tài)改變,除非遇到return語句或者拋出錯(cuò)誤。也就是說,只有async函數(shù)內(nèi)部的異步操作執(zhí)行完,才會執(zhí)行then方法指定的回調(diào)函數(shù)。
async function getTitle(url) {let response = await fetch(url);let html = await response.text();return html.match(/<title>([\s\S]+)<\/title>/i)[1]; } getTitle('https://tc39.github.io/ecma262/').then(console.log) // "ECMAScript 2017 Language Specification"上面代碼中,函數(shù)getTitle內(nèi)部有三個(gè)操作:抓取網(wǎng)頁、取出文本、匹配頁面標(biāo)題。只有這三個(gè)操作全部完成,才會執(zhí)行then方法里面的console.log。
await 命令
正常情況下,await命令后面是一個(gè) Promise 對象,返回該對象的結(jié)果。如果不是 Promise 對象,就直接返回對應(yīng)的值。
async function f() {// 等同于// return 123;return await 123; }f().then(v => console.log(v)) // 123上面代碼中,await命令的參數(shù)是數(shù)值123,這時(shí)等同于return 123。
另一種情況是,await命令后面是一個(gè)thenable對象(即定義then方法的對象),那么await會將其等同于 Promise 對象。
1 class Sleep { 2 constructor(timeout) { 3 this.timeout = timeout; 4 } 5 then(resolve, reject) { 6 const startTime = Date.now(); 7 setTimeout( 8 () => resolve(Date.now() - startTime), 9 this.timeout 10 ); 11 } 12 } 13 14 (async () => { 15 const actualTime = await new Sleep(1000); 16 console.log(actualTime); 17 })();上面代碼中,await命令后面是一個(gè)Sleep對象的實(shí)例。這個(gè)實(shí)例不是 Promise 對象,但是因?yàn)槎x了then方法,await會將其視為Promise處理。
await命令后面的 Promise 對象如果變?yōu)閞eject狀態(tài),則reject的參數(shù)會被catch方法的回調(diào)函數(shù)接收到。
async function f() {await Promise.reject('出錯(cuò)了'); }f() .then(v => console.log(v)) .catch(e => console.log(e)) // 出錯(cuò)了注意,上面代碼中,await語句前面沒有return,但是reject方法的參數(shù)依然傳入了catch方法的回調(diào)函數(shù)。這里如果在await前面加上return,效果是一樣的。
任何一個(gè)await語句后面的 Promise 對象變?yōu)閞eject狀態(tài),那么整個(gè)async函數(shù)都會中斷執(zhí)行。
async function f() {await Promise.reject('出錯(cuò)了');await Promise.resolve('hello world'); // 不會執(zhí)行 }上面代碼中,第二個(gè)await語句是不會執(zhí)行的,因?yàn)榈谝粋€(gè)await語句狀態(tài)變成了reject。
有時(shí),我們希望即使前一個(gè)異步操作失敗,也不要中斷后面的異步操作。這時(shí)可以將第一個(gè)await放在try...catch結(jié)構(gòu)里面,這樣不管這個(gè)異步操作是否成功,第二個(gè)await都會執(zhí)行。
async function f() {try {await Promise.reject('出錯(cuò)了');} catch(e) {}return await Promise.resolve('hello world'); }f() .then(v => console.log(v)) // hello world另一種方法是await后面的 Promise 對象再跟一個(gè)catch方法,處理前面可能出現(xiàn)的錯(cuò)誤。
async function f() {await Promise.reject('出錯(cuò)了').catch(e => console.log(e));return await Promise.resolve('hello world'); }f() .then(v => console.log(v)) // 出錯(cuò)了 // hello world錯(cuò)誤處理
如果await后面的異步操作出錯(cuò),那么等同于async函數(shù)返回的 Promise 對象被reject。
async function f() {await new Promise(function (resolve, reject) {throw new Error('出錯(cuò)了');}); }f() .then(v => console.log(v)) .catch(e => console.log(e)) // Error:出錯(cuò)了上面代碼中,async函數(shù)f執(zhí)行后,await后面的 Promise 對象會拋出一個(gè)錯(cuò)誤對象,導(dǎo)致catch方法的回調(diào)函數(shù)被調(diào)用,它的參數(shù)就是拋出的錯(cuò)誤對象。具體的執(zhí)行機(jī)制,可以參考后文的“async 函數(shù)的實(shí)現(xiàn)原理”。
防止出錯(cuò)的方法,也是將其放在try...catch代碼塊之中。
async function f() {try {await new Promise(function (resolve, reject) {throw new Error('出錯(cuò)了');});} catch(e) {}return await('hello world'); }如果有多個(gè)await命令,可以統(tǒng)一放在try...catch結(jié)構(gòu)中。
1 async function main() { 2 try { 3 const val1 = await firstStep(); 4 const val2 = await secondStep(val1); 5 const val3 = await thirdStep(val1, val2); 6 7 console.log('Final: ', val3); 8 } 9 catch (err) { 10 console.error(err); 11 } 12 }下面的例子使用try...catch結(jié)構(gòu),實(shí)現(xiàn)多次重復(fù)嘗試。
1 const superagent = require('superagent'); 2 const NUM_RETRIES = 3; 3 4 async function test() { 5 let i; 6 for (i = 0; i < NUM_RETRIES; ++i) { 7 try { 8 await superagent.get('http://google.com/this-throws-an-error'); 9 break; 10 } catch(err) {} 11 } 12 console.log(i); // 3 13 } 14 15 test();上面代碼中,如果await操作成功,就會使用break語句退出循環(huán);如果失敗,會被catch語句捕捉,然后進(jìn)入下一輪循環(huán)。這個(gè)操作很神奇啊。
使用注意點(diǎn)?
第一點(diǎn),前面已經(jīng)說過,await命令后面的Promise對象,運(yùn)行結(jié)果可能是rejected,所以最好把await命令放在try...catch代碼塊中。
1 async function myFunction() { 2 try { 3 await somethingThatReturnsAPromise(); 4 } catch (err) { 5 console.log(err); 6 } 7 } 8 9 // 另一種寫法 10 11 async function myFunction() { 12 await somethingThatReturnsAPromise() 13 .catch(function (err) { 14 console.log(err); 15 }); 16 }第二點(diǎn),多個(gè)await命令后面的異步操作,如果不存在繼發(fā)關(guān)系,最好讓它們同時(shí)觸發(fā)。
let foo = await getFoo(); let bar = await getBar();上面代碼中,getFoo和getBar是兩個(gè)獨(dú)立的異步操作(即互不依賴),被寫成繼發(fā)關(guān)系。這樣比較耗時(shí),因?yàn)橹挥術(shù)etFoo完成以后,才會執(zhí)行g(shù)etBar,完全可以讓它們同時(shí)觸發(fā)。
// 寫法一 let [foo, bar] = await Promise.all([getFoo(), getBar()]);// 寫法二 let fooPromise = getFoo(); let barPromise = getBar(); let foo = await fooPromise; let bar = await barPromise;上面兩種寫法,getFoo和getBar都是同時(shí)觸發(fā),這樣就會縮短程序的執(zhí)行時(shí)間。
第三點(diǎn),await命令只能用在async函數(shù)之中,如果用在普通函數(shù),就會報(bào)錯(cuò)。
async function dbFuc(db) {let docs = [{}, {}, {}];// 報(bào)錯(cuò)docs.forEach(function (doc) {await db.post(doc);}); }上面代碼會報(bào)錯(cuò),因?yàn)閍wait用在普通函數(shù)之中了。但是,如果將forEach方法的參數(shù)改成async函數(shù),也有問題。
function dbFuc(db) { //這里不需要 asynclet docs = [{}, {}, {}];// 可能得到錯(cuò)誤結(jié)果docs.forEach(async function (doc) {await db.post(doc);}); }上面代碼可能不會正常工作,原因是這時(shí)三個(gè)db.post操作將是并發(fā)執(zhí)行,也就是同時(shí)執(zhí)行,而不是繼發(fā)執(zhí)行。正確的寫法是采用for循環(huán)。
async function dbFuc(db) {let docs = [{}, {}, {}];for (let doc of docs) {await db.post(doc);} }如果確實(shí)希望多個(gè)請求并發(fā)執(zhí)行,可以使用Promise.all方法。當(dāng)三個(gè)請求都會resolved時(shí),下面兩種寫法效果相同。
1 async function dbFuc(db) { 2 let docs = [{}, {}, {}]; 3 let promises = docs.map((doc) => db.post(doc)); 4 5 let results = await Promise.all(promises); 6 console.log(results); 7 } 8 9 // 或者使用下面的寫法 10 11 async function dbFuc(db) { 12 let docs = [{}, {}, {}]; 13 let promises = docs.map((doc) => db.post(doc)); 14 15 let results = []; 16 for (let promise of promises) { 17 results.push(await promise); 18 } 19 console.log(results); 20 }目前,esm模塊加載器支持頂層await,即await命令可以不放在 async 函數(shù)里面,直接使用。
// async 函數(shù)的寫法 const start = async () => {const res = await fetch('google.com');return res.text(); };start().then(console.log);// 頂層 await 的寫法 const res = await fetch('google.com'); console.log(await res.text());上面代碼中,第二種寫法的腳本必須使用esm加載器,才會生效。
第四點(diǎn),async 函數(shù)可以保留運(yùn)行堆棧。
const a = () => {b().then(() => c()); };上面代碼中,函數(shù)a內(nèi)部運(yùn)行了一個(gè)異步任務(wù)b()。當(dāng)b()運(yùn)行的時(shí)候,函數(shù)a()不會中斷,而是繼續(xù)執(zhí)行。等到b()運(yùn)行結(jié)束,可能a()早就運(yùn)行結(jié)束了,b()所在的上下文環(huán)境已經(jīng)消失了。如果b()或c()報(bào)錯(cuò),錯(cuò)誤堆棧將不包括a()。
現(xiàn)在將這個(gè)例子改成async函數(shù)。
const a = async () => {await b();c(); };上面代碼中,b()運(yùn)行的時(shí)候,a()是暫停執(zhí)行,上下文環(huán)境都保存著。一旦b()或c()報(bào)錯(cuò),錯(cuò)誤堆棧將包括a()。
4.async 函數(shù)的實(shí)現(xiàn)原理
async 函數(shù)的實(shí)現(xiàn)原理,就是將 Generator 函數(shù)和自動執(zhí)行器,包裝在一個(gè)函數(shù)里。
async function fn(args) {// ... }// 等同于function fn(args) {return spawn(function* () {// ... }); }所有的async函數(shù)都可以寫成上面的第二種形式,其中的spawn函數(shù)就是自動執(zhí)行器。
下面給出spawn函數(shù)的實(shí)現(xiàn),基本就是前文自動執(zhí)行器的翻版。
1 function spawn(genF) { 2 return new Promise(function(resolve, reject) { 3 const gen = genF(); 4 function step(nextF) { 5 let next; 6 try { 7 next = nextF(); 8 } catch(e) { 9 return reject(e); 10 } 11 if(next.done) { 12 return resolve(next.value); 13 } 14 Promise.resolve(next.value).then(function(v) { 15 step(function() { return gen.next(v); }); 16 }, function(e) { 17 step(function() { return gen.throw(e); }); 18 }); 19 } 20 step(function() { return gen.next(undefined); }); 21 }); 22 }5.與其他異步處理方法的比較
我們通過一個(gè)例子,來看 async 函數(shù)與 Promise、Generator 函數(shù)的比較。
假定某個(gè) DOM 元素上面,部署了一系列的動畫,前一個(gè)動畫結(jié)束,才能開始后一個(gè)。如果當(dāng)中有一個(gè)動畫出錯(cuò),就不再往下執(zhí)行,返回上一個(gè)成功執(zhí)行的動畫的返回值。
首先是 Promise 的寫法。
1 function chainAnimationsPromise(elem, animations) { 2 3 // 變量ret用來保存上一個(gè)動畫的返回值 4 let ret = null; 5 6 // 新建一個(gè)空的Promise 7 let p = Promise.resolve(); 8 9 // 使用then方法,添加所有動畫 10 for(let anim of animations) { 11 p = p.then(function(val) { 12 ret = val; 13 return anim(elem); 14 }); 15 } 16 17 // 返回一個(gè)部署了錯(cuò)誤捕捉機(jī)制的Promise 18 return p.catch(function(e) { 19 /* 忽略錯(cuò)誤,繼續(xù)執(zhí)行 */ 20 }).then(function() { 21 return ret; 22 }); 23 24 }雖然 Promise 的寫法比回調(diào)函數(shù)的寫法大大改進(jìn),但是一眼看上去,代碼完全都是 Promise 的 API(then、catch等等),操作本身的語義反而不容易看出來。
接著是 Generator 函數(shù)的寫法。
1 function chainAnimationsGenerator(elem, animations) { 2 3 return spawn(function*() { 4 let ret = null; 5 try { 6 for(let anim of animations) { 7 ret = yield anim(elem); 8 } 9 } catch(e) { 10 /* 忽略錯(cuò)誤,繼續(xù)執(zhí)行 */ 11 } 12 return ret; 13 }); 14 15 }上面代碼使用 Generator 函數(shù)遍歷了每個(gè)動畫,語義比 Promise 寫法更清晰,用戶定義的操作全部都出現(xiàn)在spawn函數(shù)的內(nèi)部。這個(gè)寫法的問題在于,必須有一個(gè)任務(wù)運(yùn)行器,自動執(zhí)行 Generator 函數(shù),上面代碼的spawn函數(shù)就是自動執(zhí)行器,它返回一個(gè) Promise 對象,而且必須保證yield語句后面的表達(dá)式,必須返回一個(gè) Promise。
最后是 async 函數(shù)的寫法。
1 async function chainAnimationsAsync(elem, animations) { 2 let ret = null; 3 try { 4 for(let anim of animations) { 5 ret = await anim(elem); 6 } 7 } catch(e) { 8 /* 忽略錯(cuò)誤,繼續(xù)執(zhí)行 */ 9 } 10 return ret; 11 }可以看到 Async 函數(shù)的實(shí)現(xiàn)最簡潔,最符合語義,幾乎沒有語義不相關(guān)的代碼。它將 Generator 寫法中的自動執(zhí)行器,改在語言層面提供,不暴露給用戶,因此代碼量最少。如果使用 Generator 寫法,自動執(zhí)行器需要用戶自己提供。
6.實(shí)例:按順序完成異步操作
實(shí)際開發(fā)中,經(jīng)常遇到一組異步操作,需要按照順序完成。比如,依次遠(yuǎn)程讀取一組 URL,然后按照讀取的順序輸出結(jié)果。
Promise 的寫法如下。
1 function logInOrder(urls) { 2 // 遠(yuǎn)程讀取所有URL 3 const textPromises = urls.map(url => { 4 return fetch(url).then(response => response.text()); 5 }); 6 7 // 按次序輸出 8 textPromises.reduce((chain, textPromise) => { 9 return chain.then(() => textPromise) 10 .then(text => console.log(text)); 11 }, Promise.resolve()); 12 }上面代碼使用fetch方法,同時(shí)遠(yuǎn)程讀取一組 URL。每個(gè)fetch操作都返回一個(gè) Promise 對象,放入textPromises數(shù)組。然后,reduce方法依次處理每個(gè) Promise 對象,然后使用then,將所有 Promise 對象連起來,因此就可以依次輸出結(jié)果。
這種寫法不太直觀,可讀性比較差。下面是 async 函數(shù)實(shí)現(xiàn)。
async function logInOrder(urls) {for (const url of urls) {const response = await fetch(url);console.log(await response.text());} }上面代碼確實(shí)大大簡化,問題是所有遠(yuǎn)程操作都是繼發(fā)。只有前一個(gè) URL 返回結(jié)果,才會去讀取下一個(gè) URL,這樣做效率很差,非常浪費(fèi)時(shí)間。我們需要的是并發(fā)發(fā)出遠(yuǎn)程請求。
1 async function logInOrder(urls) { 2 // 并發(fā)讀取遠(yuǎn)程URL 3 const textPromises = urls.map(async url => { 4 const response = await fetch(url); 5 return response.text(); 6 }); 7 8 // 按次序輸出 9 for (const textPromise of textPromises) { 10 console.log(await textPromise); 11 } 12 }上面代碼中,雖然map方法的參數(shù)是async函數(shù),但它是并發(fā)執(zhí)行的,因?yàn)?span style="color:#ff0000;">只有async函數(shù)內(nèi)部是繼發(fā)執(zhí)行,外部不受影響。后面的for..of循環(huán)內(nèi)部使用了await,因此實(shí)現(xiàn)了按順序輸出。
7.異步遍歷器
《遍歷器》一章說過,Iterator 接口是一種數(shù)據(jù)遍歷的協(xié)議,只要調(diào)用遍歷器對象的next方法,就會得到一個(gè)對象,表示當(dāng)前遍歷指針?biāo)诘哪莻€(gè)位置的信息。next方法返回的對象的結(jié)構(gòu)是{value, done},其中value表示當(dāng)前的數(shù)據(jù)的值,done是一個(gè)布爾值,表示遍歷是否結(jié)束。
這里隱含著一個(gè)規(guī)定,next方法必須是同步的,只要調(diào)用就必須立刻返回值。也就是說,一旦執(zhí)行next方法,就必須同步地得到value和done這兩個(gè)屬性。如果遍歷指針正好指向同步操作,當(dāng)然沒有問題,但對于異步操作,就不太合適了。目前的解決方法是,Generator 函數(shù)里面的異步操作,返回一個(gè) Thunk 函數(shù)或者 Promise 對象,即value屬性是一個(gè) Thunk 函數(shù)或者 Promise 對象,等待以后返回真正的值,而done屬性則還是同步產(chǎn)生的。
ES2018?引入了“異步遍歷器”(Async Iterator),為異步操作提供原生的遍歷器接口,即value和done這兩個(gè)屬性都是異步產(chǎn)生。
異步遍歷的接口
異步遍歷器的最大的語法特點(diǎn),就是調(diào)用遍歷器的next方法,返回的是一個(gè) Promise 對象。
asyncIterator.next().then(({ value, done }) => /* ... */);上面代碼中,asyncIterator是一個(gè)異步遍歷器,調(diào)用next方法以后,返回一個(gè) Promise 對象。因此,可以使用then方法指定,這個(gè) Promise 對象的狀態(tài)變?yōu)閞esolve以后的回調(diào)函數(shù)。回調(diào)函數(shù)的參數(shù),則是一個(gè)具有value和done兩個(gè)屬性的對象,這個(gè)跟同步遍歷器是一樣的。
我們知道,一個(gè)對象的同步遍歷器的接口,部署在Symbol.iterator屬性上面。同樣地,對象的異步遍歷器接口,部署在Symbol.asyncIterator屬性上面。不管是什么樣的對象,只要它的Symbol.asyncIterator屬性有值,就表示應(yīng)該對它進(jìn)行異步遍歷。
下面是一個(gè)異步遍歷器的例子。
1 const asyncIterable = createAsyncIterable(['a', 'b']); 2 const asyncIterator = asyncIterable[Symbol.asyncIterator](); 3 4 asyncIterator 5 .next() 6 .then(iterResult1 => { 7 console.log(iterResult1); // { value: 'a', done: false } 8 return asyncIterator.next(); 9 }) 10 .then(iterResult2 => { 11 console.log(iterResult2); // { value: 'b', done: false } 12 return asyncIterator.next(); 13 }) 14 .then(iterResult3 => { 15 console.log(iterResult3); // { value: undefined, done: true } 16 });了解一下,異步遍歷器不再深究。
for await...of
前面介紹過,for...of循環(huán)用于遍歷同步的 Iterator 接口。新引入的for await...of循環(huán),則是用于遍歷異步的 Iterator 接口。
async function f() {for await (const x of createAsyncIterable(['a', 'b'])) {console.log(x);} } // a // b異步 Generator 函數(shù)
?就像 Generator 函數(shù)返回一個(gè)同步遍歷器對象一樣,異步 Generator 函數(shù)的作用,是返回一個(gè)異步遍歷器對象。
yield* 語句
yield*語句也可以跟一個(gè)異步遍歷器。
async function* gen1() {yield 'a';yield 'b';return 2; }async function* gen2() {// result 最終會等于 2const result = yield* gen1(); }上面代碼中,gen2函數(shù)里面的result變量,最后的值是2。
與同步 Generator 函數(shù)一樣,for await...of循環(huán)會展開yield*。
沒有最好的方法,只有最適合的方法。
轉(zhuǎn)載于:https://www.cnblogs.com/jixiaohua/p/10674686.html
總結(jié)
以上是生活随笔為你收集整理的ES6学习笔记(十六)async函数的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 巴西改装PASAM冲锋枪
- 下一篇: ansible模块---续