Skip to content

Commit 7fab96c

Browse files
committed
docs(async): 增加 Stream 异步遍历器的例子
1 parent 2430650 commit 7fab96c

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

docs/async.md

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -799,6 +799,37 @@ async function () {
799799
// b
800800
```
801801

802+
Node v10 支持异步遍历器,Stream 就部署了这个接口。下面是读取文件的传统写法与异步遍历器写法的差异。
803+
804+
```javascript
805+
// 传统写法
806+
function main(inputFilePath) {
807+
const readStream = fs.createReadStream(
808+
inputFilePath,
809+
{ encoding: 'utf8', highWaterMark: 1024 }
810+
);
811+
readStream.on('data', (chunk) => {
812+
console.log('>>> '+chunk);
813+
});
814+
readStream.on('end', () => {
815+
console.log('### DONE ###');
816+
});
817+
}
818+
819+
// 异步遍历器写法
820+
async function main(inputFilePath) {
821+
const readStream = fs.createReadStream(
822+
inputFilePath,
823+
{ encoding: 'utf8', highWaterMark: 1024 }
824+
);
825+
826+
for await (const chunk of readStream) {
827+
console.log('>>> '+chunk);
828+
}
829+
console.log('### DONE ###');
830+
}
831+
```
832+
802833
### 异步 Generator 函数
803834

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

0 commit comments

Comments
 (0)