同步遍历器的问题
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是一个遍历器(iterator)。每次调用it.next()方法,就返回一个对象,表示当前遍历位置的信息。
这里隐含着一个规定,it.next()方法必须是同步的,只要调用就必须立刻返回值。也就是说,一旦执行it.next()方法,就必须同步地得到value和done这两个属性。如果遍历指针正好指向同步操作,当然没有问题,但对于异步操作,就不太合适了。
目前的解决方法是,将异步操作包装成 Thunk 函数或者 Promise 对象,即next()方法返回值的value属性是一个 Thunk 函数或者 Promise 对象,等待以后返回真正的值,而done属性则还是同步产生的。
ES2018 引入了“异步遍历器”(Async Iterator),为异步操作提供原生的遍历器接口,即value和done这两个属性都是异步产生。
异步 Generator 函数
就像 Generator 函数返回一个同步遍历器对象一样,异步 Generator 函数的作用,是返回一个异步遍历器对象。
async function* gen() {
yield 'hello';
}
const genObj = gen();
genObj.next().then(x => console.log(x));
// { value: 'hello', done: false }
// gen是一个异步 Generator 函数,执行后返回一个异步 Iterator 对象。
// 对该对象调用next方法,返回一个 Promise 对象。
异步遍历器的设计目的之一,就是 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);
}
}
第一个参数是可遍历对象iterable,第二个参数是一个回调函数func。map的作用是将iterable每一步返回的值,使用func进行处理。
异步 Generator 函数内部,能够同时使用await和yield命令。可以这样理解,await命令用于将外部操作产生的值输入函数内部,yield命令用于将函数内部的值输出。
异步 Generator 函数可以与for await...of循环结合起来使用
// readLines 就是一个异步 Generator 函数 返回一个异步遍历器对象
// 使用 for await...of执行
(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 函数中,跟在yield命令后面的,应该是一个 Promise 对象
// 此例中yield命令后面是一个字符串,会被自动包装成一个 Promise 对象
}
如果异步 Generator 函数抛出错误,会导致 Promise 对象的状态变为reject,然后抛出的错误被catch方法捕获
async function* asyncGenerator() {
throw new Error('Problem!');
}
asyncGenerator()
.next()
.catch(err => console.log(err)); // Error: Problem!
async 函数和异步 Generator 函数,是封装异步操作的两种方法,都用来达到同一种目的。区别在于,前者自带执行器,后者通过for await...of执行,或者自己编写执行器。下面就是一个异步 Generator 函数的执行器。
async function takeAsync(asyncIterable, count = Infinity) {
const result = [];
const iterator = asyncIterable[Symbol.asyncIterator]();
// 同步遍历器存在这个等式:g() === g[Symbol.iterator]()
// 所以上面可以写为 const iterator = asyncIterable()
while (result.length < count) {
const {value, done} = await iterator.next();
if (done) break;
// 一当done为true就跳出循环 返回 result
result.push(value);
}
return result;
}
// usage
async function f() {
async function* gen() {
yield 'a';
yield 'b';
yield 'c';
}
return await takeAsync(gen());
}
// 返回一个promise then函数中的接受的参数就是 await takeAsync(gen())的值
// 即一个 yield 后面的值的组成的数组
f().then(function (result) {
console.log(result); // ['a', 'b', 'c']
})
异步 Generator 函数也可以通过next方法的参数,接收外部传入的数据。同步的数据结构,也可以使用异步 Generator 函数。
异步遍历器对象
异步遍历器的最大的语法特点,就是调用遍历器的next方法,返回的是一个 Promise 对象。
这个 Promise 对象的状态变为resolve以后的回调函数。回调函数的参数,则是一个具有value和done两个属性的对象,这个跟同步遍历器是一样的。
一个对象的同步遍历器的接口,部署在Symbol.iterator属性上面。同样地,对象的异步遍历器接口,部署在Symbol.asyncIterator属性上面。不管是什么样的对象,只要它的Symbol.asyncIterator属性有值,就表示应该对它进行异步遍历。
由于异步遍历器的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 对象resolve以后再调用。这种情况下,next方法会累积起来,自动按照每一步的顺序运行下去。下面是一个例子,把所有的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
另一种用法是一次性调用所有的next方法,然后await最后一步操作。
async function runner() {
const writer = openFile('someFile.txt');
writer.next('hello');
writer.next('world');
// next方法被同步触发,使用await等待最后一步
await writer.return();
// 异步遍历器对象 也有return 方法,与同步一样,用于结束异步Generator函数
}
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
await用来处理这个 Promise 对象,一旦resolve,就把得到的值(x)传入for...of的循环体。
for await...of循环的一个用途,是部署了 asyncIterable 操作的异步接口,可以直接放入这个循环。
let body = '';
async function f() {
for await(const data of req) body += data;
const parsed = JSON.parse(body);
console.log('got', parsed);
}
// req是一个 asyncIterable 对象
如果next方法返回的 Promise 对象被reject,for await...of就会报错,要用try...catch捕捉。
// 遍历就是循环调用异步遍历器对象的next方法
async function () {
try {
for await (const x of createRejectingIterable()) {
console.log(x);
}
} catch (e) {
console.error(e);
}
}
Node v10 支持异步遍历器,Stream 就部署了这个接口。下面是读取文件的传统写法与异步遍历器写法的差异。
// 传统写法
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* 语句
yield*语句也可以跟一个异步遍历器。
与同步 Generator 函数一样,for await...of循环会展开yield*
async function* gen1() {
yield 'b';
yield 'c'
return 2;
}
async function* gen2() {
yield 'a';
// result 最终会等于 2
const result = yield* gen1();
yield 'd'
console.log(result)
return 3 // 与同步一样 此时的done为true 则不会被循环输出
}
(async function () {
for await (const x of gen2()) {
console.log(x);
}
})();
// a
// b
// c
// d
// 2