ES6標(biāo)準(zhǔn)入門 摘要 (異步遍歷器)

同步遍歷器的問(wèn)題

function idMaker() {
  let index = 0;

  return {
    next: function() {
      return { value: index++, done: false };
    }
  };
}

const it = idMaker();

it.next().value // 0
it.next().value // 1
it.next().value // 2

變量it是一個(gè)遍歷器(iterator)。每次調(diào)用it.next()方法,就返回一個(gè)對(duì)象,表示當(dāng)前遍歷位置的信息。

這里隱含著一個(gè)規(guī)定,it.next()方法必須是同步的,只要調(diào)用就必須立刻返回值。也就是說(shuō),一旦執(zhí)行it.next()方法,就必須同步地得到value和done這兩個(gè)屬性。如果遍歷指針正好指向同步操作,當(dāng)然沒(méi)有問(wèn)題,但對(duì)于異步操作,就不太合適了。

目前的解決方法是,將異步操作包裝成 Thunk 函數(shù)或者 Promise 對(duì)象,即next()方法返回值的value屬性是一個(gè) Thunk 函數(shù)或者 Promise 對(duì)象,等待以后返回真正的值,而done屬性則還是同步產(chǎn)生的。

ES2018 引入了“異步遍歷器”(Async Iterator),為異步操作提供原生的遍歷器接口,即value和done這兩個(gè)屬性都是異步產(chǎn)生。

異步 Generator 函數(shù)

就像 Generator 函數(shù)返回一個(gè)同步遍歷器對(duì)象一樣,異步 Generator 函數(shù)的作用,是返回一個(gè)異步遍歷器對(duì)象。

async function* gen() {
  yield 'hello';
}
const genObj = gen();
genObj.next().then(x => console.log(x));
// { value: 'hello', done: false }
// gen是一個(gè)異步 Generator 函數(shù),執(zhí)行后返回一個(gè)異步 Iterator 對(duì)象。
// 對(duì)該對(duì)象調(diào)用next方法,返回一個(gè) Promise 對(duì)象。

異步遍歷器的設(shè)計(jì)目的之一,就是 Generator 函數(shù)處理同步操作和異步操作時(shí),能夠使用同一套接口。

// 同步 Generator 函數(shù)
function* map(iterable, func) {
  const iter = iterable[Symbol.iterator]();
  while (true) {
    const {value, done} = iter.next();
    if (done) break;
    yield func(value);
  }
}

// 異步 Generator 函數(shù)
async function* map(iterable, func) {
  const iter = iterable[Symbol.asyncIterator]();
  while (true) {
    const {value, done} = await iter.next();
    if (done) break;
    yield func(value);
  }
}

第一個(gè)參數(shù)是可遍歷對(duì)象iterable,第二個(gè)參數(shù)是一個(gè)回調(diào)函數(shù)func。map的作用是將iterable每一步返回的值,使用func進(jìn)行處理。

異步 Generator 函數(shù)內(nèi)部,能夠同時(shí)使用await和yield命令??梢赃@樣理解,await命令用于將外部操作產(chǎn)生的值輸入函數(shù)內(nèi)部,yield命令用于將函數(shù)內(nèi)部的值輸出。

異步 Generator 函數(shù)可以與for await...of循環(huán)結(jié)合起來(lái)使用

// readLines 就是一個(gè)異步 Generator 函數(shù) 返回一個(gè)異步遍歷器對(duì)象
// 使用 for await...of執(zhí)行
(async function () {
  for await (const line of readLines(filePath)) {
    console.log(line);
  }
})()

// 例2

async function* prefixLines(asyncIterable) {
  for await (const line of asyncIterable) {
    yield '> ' + line;
  }
  // 在異步Generator 函數(shù)中,跟在yield命令后面的,應(yīng)該是一個(gè) Promise 對(duì)象
  // 此例中yield命令后面是一個(gè)字符串,會(huì)被自動(dòng)包裝成一個(gè) Promise 對(duì)象
}

如果異步 Generator 函數(shù)拋出錯(cuò)誤,會(huì)導(dǎo)致 Promise 對(duì)象的狀態(tài)變?yōu)閞eject,然后拋出的錯(cuò)誤被catch方法捕獲

async function* asyncGenerator() {
  throw new Error('Problem!');
}

asyncGenerator()
.next()
.catch(err => console.log(err)); // Error: Problem!

async 函數(shù)和異步 Generator 函數(shù),是封裝異步操作的兩種方法,都用來(lái)達(dá)到同一種目的。區(qū)別在于,前者自帶執(zhí)行器,后者通過(guò)for await...of執(zhí)行,或者自己編寫執(zhí)行器。下面就是一個(gè)異步 Generator 函數(shù)的執(zhí)行器。

async function takeAsync(asyncIterable, count = Infinity) {
  const result = [];
  const iterator = asyncIterable[Symbol.asyncIterator]();
  // 同步遍歷器存在這個(gè)等式:g() === g[Symbol.iterator]()
  // 所以上面可以寫為 const iterator = asyncIterable()
  while (result.length < count) {
    const {value, done} = await iterator.next();
    if (done) break;
    // 一當(dāng)done為true就跳出循環(huán) 返回 result
    result.push(value);
  }
  return result;
}

// usage

async function f() {
  async function* gen() {
    yield 'a';
    yield 'b';
    yield 'c';
  }

  return await takeAsync(gen());
}

// 返回一個(gè)promise then函數(shù)中的接受的參數(shù)就是 await takeAsync(gen())的值
// 即一個(gè) yield 后面的值的組成的數(shù)組

f().then(function (result) {
  console.log(result); // ['a', 'b', 'c']
})

異步 Generator 函數(shù)也可以通過(guò)next方法的參數(shù),接收外部傳入的數(shù)據(jù)。同步的數(shù)據(jù)結(jié)構(gòu),也可以使用異步 Generator 函數(shù)。

異步遍歷器對(duì)象

異步遍歷器的最大的語(yǔ)法特點(diǎn),就是調(diào)用遍歷器的next方法,返回的是一個(gè) Promise 對(duì)象。

這個(gè) Promise 對(duì)象的狀態(tài)變?yōu)閞esolve以后的回調(diào)函數(shù)?;卣{(diào)函數(shù)的參數(shù),則是一個(gè)具有value和done兩個(gè)屬性的對(duì)象,這個(gè)跟同步遍歷器是一樣的。

一個(gè)對(duì)象的同步遍歷器的接口,部署在Symbol.iterator屬性上面。同樣地,對(duì)象的異步遍歷器接口,部署在Symbol.asyncIterator屬性上面。不管是什么樣的對(duì)象,只要它的Symbol.asyncIterator屬性有值,就表示應(yīng)該對(duì)它進(jìn)行異步遍歷。

由于異步遍歷器的next方法,返回的是一個(gè) Promise 對(duì)象。因此,可以把它放在await命令后面。

async function f() {
  const asyncIterable = createAsyncIterable(['a', 'b']);
  const asyncIterator = asyncIterable[Symbol.asyncIterator]();
  console.log(await asyncIterator.next());
  // { value: 'a', done: false }
  console.log(await asyncIterator.next());
  // { value: 'b', done: false }
  console.log(await asyncIterator.next());
  // { value: undefined, done: true }
}

// next方法用await處理以后,就不必使用then方法了
// 整個(gè)流程已經(jīng)很接近同步處理了

異步遍歷器的next方法是可以連續(xù)調(diào)用的,不必等到上一步產(chǎn)生的 Promise 對(duì)象resolve以后再調(diào)用。這種情況下,next方法會(huì)累積起來(lái),自動(dòng)按照每一步的順序運(yùn)行下去。下面是一個(gè)例子,把所有的next方法放在Promise.all方法里面。

const asyncIterable = createAsyncIterable(['a', 'b']);
const asyncIterator = asyncIterable[Symbol.asyncIterator]();
const [{value: v1}, {value: v2}] = await Promise.all([
  asyncIterator.next(), asyncIterator.next()
]);

console.log(v1, v2); // a b

另一種用法是一次性調(diào)用所有的next方法,然后await最后一步操作。

async function runner() {
  const writer = openFile('someFile.txt');
  writer.next('hello');
  writer.next('world');
  // next方法被同步觸發(fā),使用await等待最后一步
  await writer.return();
  // 異步遍歷器對(duì)象 也有return 方法,與同步一樣,用于結(jié)束異步Generator函數(shù)
}

runner();

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

await用來(lái)處理這個(gè) Promise 對(duì)象,一旦resolve,就把得到的值(x)傳入for...of的循環(huán)體。

for await...of循環(huán)的一個(gè)用途,是部署了 asyncIterable 操作的異步接口,可以直接放入這個(gè)循環(huán)。

let body = '';

async function f() {
  for await(const data of req) body += data;
  const parsed = JSON.parse(body);
  console.log('got', parsed);
}

// req是一個(gè) asyncIterable 對(duì)象

如果next方法返回的 Promise 對(duì)象被reject,for await...of就會(huì)報(bào)錯(cuò),要用try...catch捕捉。

// 遍歷就是循環(huán)調(diào)用異步遍歷器對(duì)象的next方法
async function () {
  try {
    for await (const x of createRejectingIterable()) {
      console.log(x);
    }
  } catch (e) {
    console.error(e);
  }
}

Node v10 支持異步遍歷器,Stream 就部署了這個(gè)接口。下面是讀取文件的傳統(tǒng)寫法與異步遍歷器寫法的差異。

// 傳統(tǒng)寫法
function main(inputFilePath) {
  const readStream = fs.createReadStream(
    inputFilePath,
    { encoding: 'utf8', highWaterMark: 1024 }
  );
  readStream.on('data', (chunk) => {
    console.log('>>> '+chunk);
  });
  readStream.on('end', () => {
    console.log('### DONE ###');
  });
}

// 異步遍歷器寫法
async function main(inputFilePath) {
  const readStream = fs.createReadStream(
    inputFilePath,
    { encoding: 'utf8', highWaterMark: 1024 }
  );

  for await (const chunk of readStream) {
    console.log('>>> '+chunk);
  }
  console.log('### DONE ###');
}

yield* 語(yǔ)句

yield*語(yǔ)句也可以跟一個(gè)異步遍歷器。

與同步 Generator 函數(shù)一樣,for await...of循環(huán)會(huì)展開(kāi)yield*

async function* gen1() {
  yield 'b';
  yield 'c'
  return 2;
}

async function* gen2() {
  yield 'a';
  // result 最終會(huì)等于 2
  const result = yield* gen1();
  yield 'd'
  console.log(result)
  return 3 // 與同步一樣 此時(shí)的done為true 則不會(huì)被循環(huán)輸出
}

(async function () {
  for await (const x of gen2()) {
    console.log(x);
  }
})();
// a
// b
// c
// d
// 2
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 含義 async函數(shù)是Generator函數(shù)的語(yǔ)法糖,它使得異步操作變得更加方便。 寫成async函數(shù),就是下面這...
    oWSQo閱讀 2,041評(píng)論 0 2
  • async 函數(shù) 含義 ES2017 標(biāo)準(zhǔn)引入了 async 函數(shù),使得異步操作變得更加方便。 async 函數(shù)是...
    huilegezai閱讀 1,315評(píng)論 0 6
  • 本文為阮一峰大神的《ECMAScript 6 入門》的個(gè)人版提純! babel babel負(fù)責(zé)將JS高級(jí)語(yǔ)法轉(zhuǎn)義,...
    Devildi已被占用閱讀 2,131評(píng)論 0 4
  • 簡(jiǎn)介 基本概念 Generator函數(shù)是ES6提供的一種異步編程解決方案,語(yǔ)法行為與傳統(tǒng)函數(shù)完全不同。本章詳細(xì)介紹...
    呼呼哥閱讀 1,136評(píng)論 0 4
  • 在此處先列下本篇文章的主要內(nèi)容 簡(jiǎn)介 next方法的參數(shù) for...of循環(huán) Generator.prototy...
    醉生夢(mèng)死閱讀 1,486評(píng)論 3 8

友情鏈接更多精彩內(nèi)容