From 7fab96c932f93e3671f736eafc2b3db3b9088d65 Mon Sep 17 00:00:00 2001 From: ruanyf Date: Tue, 17 Apr 2018 15:53:05 +0800 Subject: [PATCH] =?UTF-8?q?docs(async):=20=E5=A2=9E=E5=8A=A0=20Stream=20?= =?UTF-8?q?=E5=BC=82=E6=AD=A5=E9=81=8D=E5=8E=86=E5=99=A8=E7=9A=84=E4=BE=8B?= =?UTF-8?q?=E5=AD=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/async.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/docs/async.md b/docs/async.md index 64d1ac1..0a12272 100644 --- a/docs/async.md +++ b/docs/async.md @@ -799,6 +799,37 @@ async function () { // b ``` +Node v10 支持异步遍历器,Stream 就部署了这个接口。下面是读取文件的传统写法与异步遍历器写法的差异。 + +```javascript +// 传统写法 +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 ###'); +} +``` + ### 异步 Generator 函数 就像 Generator 函数返回一个同步遍历器对象一样,异步 Generator 函数的作用,是返回一个异步遍历器对象。