ES6(17)异步遍历器

807 阅读6分钟

异步遍历器

Iterator 接口是一种数据遍历的协议,只要调用遍历器对象的next方法,就会得到一个对象,表示当前遍历指针所在的那个位置的信息。

这里隐含着一个规定,next方法必须是同步的,只要调用必须立刻返回值

目前的解决方法是,Generator 函数里面的异步操作,返回一个 Thunk 函数或者Promise对象,即value属性是一个Thunk函数或者Promise对象,等待以后返回真正的值,而done属性则还是同步产生的。

ES2018 引入了“异步遍历器”(Async Iterator),为异步操作提供原生的遍历器接口,即value和done这两个属性都是异步产生。

异步遍历的接口

异步遍历器的最大的语法特点:调用遍历器的next方法,返回的是一个Promise对象

asyncIterator
  .next()
  .then(
    ({ value, done }) => /* ... */
  );
1、asyncIterator是一个异步遍历器,调用next方法以后,返回一个 Promise 对象
2、因此,可以使用then方法指定,这个 Promise 对象的状态变为resolve以后的回调函数
3、回调函数的参数,则是一个具有value和done两个属性的对象,这个跟同步遍历器是一样的

同步遍历器的接口,部署在Symbol.iterator属性上面

异步遍历器接口,部署在Symbol.asyncIterator属性上面

不管是什么样的对象,只要它的Symbol.asyncIterator属性有值,就表示应该对它进行异步遍历。

示例

const asyncIterable = createAsyncIterable(['a', 'b']);
const asyncIterator = asyncIterable[Symbol.asyncIterator]();

asyncIterator
.next()
.then(iterResult1 => {
  console.log(iterResult1); // { value: 'a', done: false }
  return asyncIterator.next();
})
.then(iterResult2 => {
  console.log(iterResult2); // { value: 'b', done: false }
  return asyncIterator.next();
})
.then(iterResult3 => {
  console.log(iterResult3); // { value: undefined, done: true }
});

上面代码中,异步遍历器其实返回了两次值

第一次调用的时候,返回一个 Promise 对象;等到 Promise 对象resolve了,再返回一个表示当前数据成员信息的对象。

异步遍历器与同步遍历器最终行为是一致的,只是会先返回 Promise 对象,作为中介。

异步遍历器的next方法放在await命令后面

由于异步遍历器的next方法,返回的是一个 Promise 对象。因此,可以把它放在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方法了。

把所有的next方法放在Promise.all方法里面

异步遍历器的next方法是可以连续调用的,不必等到上一步产生的 Promise 对象resolve以后再调用。这种情况下,next方法会累积起来,自动按照每一步的顺序运行下去。

async function f() {
	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

另一种用法是一次性调用所有的next方法,然后await最后一步操作

async function runner() {
  const writer = openFile('someFile.txt');
  writer.next('hello');
  writer.next('world');
  await writer.return();
}

runner();

for await...of

for...of循环用于遍历同步的 Iterator 接口

for await...of循环,用于遍历异步的 Iterator 接口

async function f() {
  for await (const x of createAsyncIterable(['a', 'b'])) {
    console.log(x);
  }
}
// a
// b

createAsyncIterable()返回一个拥有异步遍历器接口的对象

for...of循环自动调用这个对象的异步遍历器的next方法,会得到一个Promise对象。

await用来处理这个Promise对象,一旦resolve,就把得到的值(x)传入for...of的循环体。

如果next方法返回的 Promise 对象被rejectfor await...of就会报错,要用try...catch捕捉。

async function () {
  try {
    for await (const x of createRejectingIterable()) {
      console.log(x);
    }
  } catch (e) {
    console.error(e);
  }
}

for await...of循环也可以用于同步遍历器

(async function () {
  for await (const x of ['a', 'b']) {
    console.log(x);
  }
})();
// a
// b

读取文件的传统写法与异步遍历器写法的差异

// 传统写法
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 ###');
  });
}


// 异步遍历器写法
const fs = require('fs');
async function main(filepath) {
    const redStream = fs.createReadStream(
        filepath,
        {
            encoding:'utf8',
            highWaterMark:1024
        }
    )

    for await (const chunk of redStream){
        console.log('>>>>'+chunk)
    }
    console.log('DONE')
}
main('./fileA')

异步 Generator 函数

就像Generator函数返回一个同步遍历器对象一样,异步 Generator 函数的作用,是返回一个异步遍历器对象。

在语法上

异步 Generator 函数就是async函数与 Generator 函数的结合。

//gen是一个异步 Generator 函数,执行后返回一个异步 Iterator 对象。对该对象调用next方法,返回一个 Promise 对象。
async function* gen() {
  yield 'hello';
}
const genObj = gen();
genObj.next().then(x => console.log(x));
// { value: 'hello', done: false }

异步遍历器的设计目的之一

Generator 函数处理同步操作和异步操作时,能够使用同一套接口。

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

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

上面有两个版本的map,前一个处理同步遍历器,后一个处理异步遍历器,可以看到两个版本的写法基本上是一致的。

异步 Generator 函数抛出错误,会导致 Promise 对象的状态变为reject,然后抛出的错误被catch方法捕获

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

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

异步 Generator 函数的执行器

async function takeAsync(asyncIterable, count = Infinity) {
  const result = [];
  const iterator = asyncIterable[Symbol.asyncIterator]();
  while (result.length < count) {
    const {value, done} = await iterator.next();
    if (done) break;
    result.push(value);
  }
  return result;
}

上面自动执行器的一个使用实例:

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

  return await takeAsync(gen());
}

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

JavaScript四种函数形式

普通函数、async 函数、Generator 函数和异步 Generator 函数

如果是一系列按照顺序执行的异步操作(比如读取文件,然后写入新内容,再存入硬盘),可以使用 async 函数;

如果是一系列产生相同数据结构的异步操作(比如一行一行读取文件),可以使用异步 Generator 函数。

异步 Generator 函数可以通过next方法传参

可以通过next方法的参数,接收外部传入的数据

const writer = openFile('someFile.txt');
writer.next('hello'); // 立即执行
writer.next('world'); // 立即执行
await writer.return(); // 等待写入结束

每次next方法都是同步执行的,最后的await命令用于等待整个写入操作结束。

同步的数据结构,也可以使用异步 Generator 函数

async function* createAsyncIterable(syncIterable) {
  for (const elem of syncIterable) {
    yield elem;
  }
}
//由于没有异步操作,所以也就没有使用await关键字

yield* 语句

yield*语句也可以跟一个异步遍历器

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

async function* gen2() {
  // result 最终会等于 2
  const result = yield* gen1();
}

for await...of循环会展开yield*。

(async function () {
  for await (const x of gen2()) {
    console.log(x);
  }
})();
// a
// b