You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
constfs=require('fs');constpath=require('path');constco=require('./lib/co.js');function*findLargest(dir){constfilenames=yieldreaddir(dir);conststatArray=yieldfilenames.map(filename=>getStat(dir,filename));constresult=statArray.filter(statObj=>statObj.stat.isFile()).sort((a,b)=>b.stat.size-a.stat.size);returnresult[0].file}co(findLargest,'./images').then(file=>{console.log(`largest file is ${file}`)}).catch(err=>console.error(err))// 不使用co模板constdata=findLargest('./images');data.next().value.then(filenames=>{conststatArray=data.next(filenames);returnPromise.all(statArray.value)}).then(res=>{console.log(`largest file is ${data.next(res).value}`)});
asyncfunctionfindLargest(dir){constfilenames=awaitreaddir(dir);constpromises=filenames.map(filename=>getStat(dir,filename));conststatArray=awaitPromise.all(promises);constresult=statArray.filter(statObj=>statObj.stat.isFile()).sort((a,b)=>b.stat.size-a.stat.size);returnresult[0].file}findLargest('./images').then(file=>{console.log(`largest file is ${file}`)}).catch(err=>console.error(err));
异步处理实战
以
查找指定目录下的最大文件
为例,感受下从回调函数 > Promise > Generator > Async
异步处理方式的改变
思路分析
fs.readdir
读取某个目录下所有文件列表fs.stat
读取文件信息,并保存在数组中sort
对文件的size
进行递减排序,返回最大的文件名回调函数
代码中回调嵌套着回调,代码冗余。
Promise
代码结构比回调函数的好了很多,
readdir
和getStat
可以抽离出来,逻辑也清晰了,但then
仍存在嵌套。Generator
配合
co
函数库效果更好,不使用co
的话,执行Generator函数,得到遍历器对象,调用next
方法分别执行异步任务三个阶段。Async
用了
async
无需再手动执行next
方法,基于了Generator
和Promise
的一层封装。参考文章
The text was updated successfully, but these errors were encountered: